package com.quanyan.place.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.request.ReqUserAccumulateModify;
import com.quanyan.assets.response.RespUserAccumulateModify;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.club.entity.RespClubActivity;
import com.quanyan.club.entity.RespLatesActivityInfo;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.comment.reqeust.*;
import com.quanyan.comment.response.*;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.comment.serviceFacade.UserClient;
import com.quanyan.comment.serviceFacade.UserCollectServiceFacade;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.PlatformTypeEnum;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.*;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.component.MerchantClientPayType;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.*;
import com.quanyan.place.entity.apiresp.*;
import com.quanyan.place.entity.base.apiresp.RespDistrict;
import com.quanyan.place.entity.vo.*;
import com.quanyan.place.enums.PayTypeEnum;
import com.quanyan.place.enums.SearchTypeEnum;
import com.quanyan.place.enums.SortTypeEnum;
import com.quanyan.place.mapper.*;
import com.quanyan.place.request.ReqCommentAdd;
import com.quanyan.place.response.RespPlaceElementsInfo;
import com.quanyan.place.service.*;
import com.quanyan.place.thread.SolrIndexThread;
import com.quanyan.place.utils.PlaceOrderUtil;
import com.quanyan.place.utils.PlaceUtil;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.search.entity.request.ReqPlaceSearchInfo;
import com.quanyan.search.entity.request.ReqPlaceSearchInfoNew;
import com.quanyan.search.entity.response.PlaceSearchResponse;
import com.quanyan.search.entity.response.SearchResponses;
import com.quanyan.statium.api.req.ReqLastGameEvent;
import com.quanyan.statium.api.resp.GameEventSummary;
import com.quanyan.statium.api.resp.ResPlaceGameEventMsg;
import com.quanyan.statium.api.resp.ResUserGameEvent;
import com.quanyan.statium.service.StadiumOpenService;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;
import sms.SmsApi;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_COMBINE;


/**
 * Created by jingliu on 16/5/26.
 */
@Service
public class ApiPlaceServiceImpl extends PosChangePriceServiceImpl implements ApiPlaceService {

    private static final Logger logger = LoggerFactory.getLogger(ApiPlaceServiceImpl.class);
    @Autowired
    TbBizPlaceMapper tbBizPlaceMapper;
    @Autowired
    DictMapper dictMapper;
    @Autowired
    IBaseService baseService;
    @Autowired
    TbCityMapper tbCityMapper;
    @Autowired
    TbDistrictMapper tbDistrictMapper;
    @Autowired
    TbBizPlaceUnitMapper placeUnitMapper;
    @Autowired
    TbBizPlaceAttachMapper tbBizPlaceAttachMapper;
    @Autowired
    TbPlaceImageMapper tbPlaceImageMapper;
    @Autowired
    PlaceUnitMapper placeUnitListMapper;
    @Autowired
    PlaceAttachMapper placeAttachMapper;
    @Autowired
    TbBizPlaceUnitTimeMapper tbBizPlaceUnitTimeMapper;
    @Autowired
    TbBizPlaceCategoryMapper tbBizPlaceCategoryMapper;
    @Autowired
    TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;

    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;

    @Autowired
    TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

    @Autowired
    TbBizPlaceUnitCombineMapper pucMapper;

    @Autowired
    UserClient<?> userClient;

    @Autowired

    TbLabelMapper tbLabelMapper;

    @Autowired
    ISearchService searchService;

    static Map<String, RespBizPlaceServiceInfo> bizPlaceServiceInfoMap = new ConcurrentHashMap<>();

    @Autowired
    PlaceUnitSalePlanMapper placeUnitSalePlanMapper;

    @Autowired
    CommentServiceFacade commentServiceFacade;

    @Autowired
    TbBizPlacePayItemMapper tbBizPlacePayItemMapper;

    @Autowired
    UserServiceFacade userServiceFacade;

    @Autowired
    UserAssetsService userAssetsService;

    @Autowired
    PlaceRedisTemplate placeRedisTemplate;

    @Autowired
    TbBizPlaceRuleMapper tbBizPlaceRuleMapper;

    @Autowired
    UserCollectServiceFacade userCollectServiceFacade;

    @Autowired
    TbBizPlaceUnitSalePlanMainMapper tbBizPlaceUnitSalePlanMainMapper;

    @Autowired
    ClubOpenService clubOpenService;

    @Autowired
    StadiumOpenService stadiumOpenService;

    @Autowired
    PlaceUnitCombineService placeUCService;

    @Value("${c.service.url}")
    public String cAddress;

    @Value("${place.admin.uid}")
    private Integer placeAdminUser;


    @Value("${place.share.url}")
    private String placeShareUrl;

    @Value("${place.order.share.url}")
    private String placeOrderShareUrl;

    private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Autowired
    PlaceMemberService placeMemberService;

    @Autowired
    private TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;

    @Autowired
    private TbBizPlaceMemberOpHistoryMapper tbBizPlaceMemberOpHistoryMapper;

    @Autowired
    BaseServiceImpl baseServiceimpl;

    @Autowired
    IBaseService iBaseService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    TbBizPlacePrivateOrderMapper tbBizPlacePrivateOrderMapper;

    @Autowired
    TbPlaceTicketSalePlanMapper tbPlaceTicketSalePlanMapper;

    @Autowired
    TbBusinessHibirdLogMapper tbBusinessHibirdLogMapper;

    @Autowired
    PlaceBaseService placeBaseService;

    @Autowired
    PlaceTicketService placeTicketService;

    @Autowired
    PlaceOrderService placeOrderService;

    @Autowired
    PlaceGoodsService placeGoodsService;
    @Autowired
    private PlaceMapper placeMapper;

    @Autowired
    PlaceOrderUtilService placeOrderUtilService;

    @Autowired
    TbBizPlacePayTypeMapper tbBizPlacePayTypeMapper;


    @Autowired
    com.quanyan.place.biz.SmsService  placeSmsService;

    @Autowired
    PlaceBlockBookingOrderMapper placeBlockBookingOrderMapper;

    @Autowired
    FinanceService financeService;

    public APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> searchPlaceList(Integer uid, ReqSearchVo reqSearchVo) {
        if (StringUtils.isEmpty(uid)) {
            return APIResponse.returnSuccess(null);
        }
        int oldPageNum = reqSearchVo.getPageNum();
        int oldPageSize = reqSearchVo.getPageSize();
        TbBizPlaceOrderExample orderExample = new TbBizPlaceOrderExample();
        orderExample.createCriteria().andUidEqualTo(uid).andIsEffectiveEqualTo(PlaceConstants.IS_EFFECTIVE_YES);
        orderExample.setDistinct(true);
        List<TbBizPlaceOrder> orders = this.tbBizPlaceOrderMapper.selectByExample(orderExample);
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(orders)) {
            final List<Integer> ids = new ArrayList<>();
            for (TbBizPlaceOrder tbBizPlaceOrder : orders) {
                if (!ids.contains(tbBizPlaceOrder.getPlaceId())) {
                    ids.add(tbBizPlaceOrder.getPlaceId());
                }
            }

            reqSearchVo.setPageNum(0);
            reqSearchVo.setPageSize(1000);
            APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> pageObjs = searchByDb(reqSearchVo);
            if (pageObjs.isRet() && !StringUtils.isEmpty(pageObjs.getData())) {
                List<RespBizPlaceBaseInfo> respBizPlaceBaseInfos = pageObjs.getData().getItems();
                Predicate<RespBizPlaceBaseInfo> predicate = new Predicate<RespBizPlaceBaseInfo>() {
                    @Override
                    public boolean apply(@Nullable RespBizPlaceBaseInfo input) {
                        input.setIsOrders(1);
                        return ids.contains(input.getId());
                    }
                };
                Collection<RespBizPlaceBaseInfo> collection = Collections2.filter(respBizPlaceBaseInfos, predicate);
                if (CollectionUtils.isNotEmpty(collection)) {
                    List<RespBizPlaceBaseInfo> list = Lists.newArrayList(collection);
                    List<RespBizPlaceBaseInfo> respBizPlaceBaseInfos1 = this.fenye(list, oldPageNum, oldPageSize);
                    PageObj<List<RespBizPlaceBaseInfo>> pageObj = new PageObj<>();
                    pageObj.setItems(respBizPlaceBaseInfos1);
                    pageObj.setPageNum(oldPageNum);
                    pageObj.setSize(oldPageSize);
                    pageObj.setTotal(list.size());

                    if (StringUtils.isEmpty(pageObj) && CollectionUtils.isEmpty(pageObj.getItems())) {
                        return APIResponse.returnSuccess(null);
                    }
                    return APIResponse.returnSuccess(pageObj);
                }
            }
        }
        return APIResponse.returnSuccess(null);
    }


    /**
     * 调用搜索引擎返回场馆信息列表
     */
    @Override
    public APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> searchPlaceList(ReqSearchVo reqSearchVo) {
        StopWatch stopWatch = new StopWatch();
        logger.info("===================搜索条件===========reqSearchVo: {}", JSON.toJSONString(reqSearchVo));
        stopWatch.start("1");
        ReqPlaceSearchInfo reqPlaceSearchInfo = this.searchService.getReqPlaceSearchInfo(reqSearchVo);
        logger.info("===================转换搜索对象===========ReqPlaceSearchInfo:{}",
                JSON.toJSONString(reqPlaceSearchInfo));
//        if (StringUtils.isEmpty(reqSearchVo.getPageNum()) || reqSearchVo.getPageNum().intValue()==Constants.DEFAULT_PAGE_NUM){
//            reqSearchVo.setPageNum(Constants.DEFAULT_PAGE_INDEX);
//        }
        stopWatch.stop();
        stopWatch.start("2");
        APIResponse<SearchResponses<List<PlaceSearchResponse>>> response = this.searchService.listSearch(reqPlaceSearchInfo);
        logger.info("===================调用搜索引擎===========APIResponse<List<PlaceSearchResponse>>:{}",
                JSON.toJSONString(response));
        stopWatch.stop();
        stopWatch.start("3");
        if (!response.isRet()) {
            logger.error("===================调用搜索引擎失败===========ReqPlaceSearchInfo:{}",
                    JSON.toJSONString(reqPlaceSearchInfo));
            return APIResponse.returnFail("没有记录");
        }
        List<PlaceSearchResponse> list = response.getData().getData();
        if (CollectionUtils.isEmpty(list)) {
            logger.warn("===================调用搜索引擎查询无结果===========ReqPlaceSearchInfo:{}",
                    JSON.toJSONString(reqPlaceSearchInfo));
            return APIResponse.returnSuccess(null);
        }
        Integer total = response.getData().getTotal();
        //传入reqSearchVo
        List<RespBizPlaceBaseInfo> respBizPlaceBaseInfos = this.searchService.getSearchBizPlaceBaseInfos(list, reqSearchVo, null);
        Integer pageNum = reqSearchVo.getPageNum();
        if (pageNum == null) {
            pageNum = Constants.DEFAULT_PAGE_NUM;
        }

        Integer pageSize = reqSearchVo.getPageSize();
        if (pageSize == null) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        PageObj<List<RespBizPlaceBaseInfo>> pageObj = PageObj.create(total, pageNum,
                pageSize, respBizPlaceBaseInfos);
        stopWatch.stop();
        logger.info(stopWatch.prettyPrint());
        return APIResponse.returnSuccess(pageObj);
    }


    @Override
    public APIResponse<List<RespPlaceElementsInfo>> commentType(Integer placeId) {
        if (StringUtils.isEmpty(userClient)) {
            logger.error("===================userClient异常===========");
            return APIResponse.returnFail("没有获取到评价服务");
        }
        APIResponse<List<RespPlaceElementsInfo>> response = new APIResponse<List<RespPlaceElementsInfo>>();
        ReqCommentQuery reqCommentQuery = new ReqCommentQuery();
        reqCommentQuery.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        reqCommentQuery.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqCommentQuery.setBusinessId(placeId);
        logger.debug("===================ReqCommentQuery:{}", JSON.toJSONString(reqCommentQuery));
        APIResponse<List<RespCommentDetail>> apiResponse = commentServiceFacade
                .getCommentDetailPro(Constants.PLACE_BOOKING_CODE, 1);//Todo:BusinessId目前写死，数据库里需要手动配置
        logger.debug("===================APIResponse:{}", JSON.toJSONString(apiResponse));
        if (!apiResponse.isRet()) {
            logger.error("===================调用获取评价元素异常 ReqCommentQuery:{}", JSON.toJSONString(reqCommentQuery));
            return APIResponse.returnFail("调用评价服务失败");
        }
        List<RespCommentDetail> datas = apiResponse.getData();
        if (CollectionUtils.isEmpty(datas)) {
            logger.warn("===================没有对应的评价项目placeId:{}", placeId);
            return APIResponse.returnSuccess(null);
        }
        List<RespPlaceElementsInfo> elementsInfos = new ArrayList<>();
        for (RespCommentDetail respCommentDetail : datas) {
            RespPlaceElementsInfo respPlaceElementsInfo = new RespPlaceElementsInfo();
            respPlaceElementsInfo.setId(respCommentDetail.getCommentDetailId());
            respPlaceElementsInfo.setName(respCommentDetail.getCommentDetailName());
            elementsInfos.add(respPlaceElementsInfo);
        }
        BeanUtils.copyProperties(apiResponse, response);
        response.setData(elementsInfos);
        return response;
    }

    @Override
    @NotNull(message = "场馆评价对象不能为空")
    public APIResponse<Integer> comment(ReqCommentAdd reqCommentAdd) {
        if (baseService.hasComment(reqCommentAdd.getUid(), reqCommentAdd.getPlaceId(), reqCommentAdd.getOrderId())) {
            return APIResponse.returnFail("评价失败，该订单已经完成评价!");
        }

        //调用评价服务并加积分
        ReqCommentParam reqCommentParam = new ReqCommentParam();
        reqCommentParam.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        reqCommentParam.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqCommentParam.setCommentType(Constants.USER_COMMENT_TYPE);
        reqCommentParam.setBusinessId(reqCommentAdd.getPlaceId());
        reqCommentParam.setFromUserId(reqCommentAdd.getUid());
        reqCommentParam.setOrderNo(reqCommentAdd.getOrderId());
        if (StringUtils.isEmpty(reqCommentAdd.getCommentContent())) {
            return APIResponse.returnFail("评论不能为空！");
        }
        reqCommentParam.setCommentContent(reqCommentAdd.getCommentContent());
        List<RespPlaceElementsInfo> elementsInfos = reqCommentAdd.getCommentTypeList();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Double scoreSum = 0d;
        for (RespPlaceElementsInfo respPlaceElementsInfo : elementsInfos) {
            ReqCommentDetailScore reqCommentDetailScore = new ReqCommentDetailScore();
            reqCommentDetailScore.setCommentDetailId(respPlaceElementsInfo.getId());
            Double score =
                    StringUtils.isEmpty(respPlaceElementsInfo.getScore()) ? PlaceConstants.COMMENT_DEFAULT_VALUE
                            : respPlaceElementsInfo.getScore();
            scoreSum += score;
            reqCommentDetailScore.setScore(Double.parseDouble(score + ""));
            list.add(reqCommentDetailScore.toMap());
        }
        reqCommentParam.setLstCommentDetailScore(list);
        APIResponse apiResponse = commentServiceFacade.commentAdd(reqCommentParam);
        logger.debug("==============调用评价服务 ReqCommentParam:{}", JSON.toJSONString(reqCommentParam));
        if (!apiResponse.isRet()) {
            logger.error("==============调用评价服务异常 ReqCommentParam:{}", JSON.toJSONString(reqCommentParam));
            return APIResponse.returnFail("调用评价服务失败");
        }
        APIResponse response = new APIResponse();
        BeanUtils.copyProperties(apiResponse, response);
        if (apiResponse.getErrcode() == ApiResponseEnum.SUCCESS.getId()) {
            if (!modBizPlace(scoreSum / elementsInfos.size(), reqCommentAdd.getPlaceId())) {
                logger.error("==============更新评论人数、总分数失败 scoreSum:{}===PlaceId:{}", scoreSum / elementsInfos.size(),
                        reqCommentAdd.getPlaceId());
                return APIResponse.returnFail("更新评论人数、总分数失败");
            }
            //2、调用评价送积分
            com.quanyan.api.APIRequest<ReqUserAccumulateModify> userApiRequest = new com.quanyan.api.APIRequest<ReqUserAccumulateModify>();
            ReqUserAccumulateModify reqUserAccumulateModify = new ReqUserAccumulateModify();
            reqUserAccumulateModify.setSystemCode(Constants.PLACE_SYSTEM_CODE);
            reqUserAccumulateModify.setBusinessCode(PlaceConstants.COMMENT_SERVICE_CODE);
            reqUserAccumulateModify.setUid(reqCommentAdd.getUid());
            reqUserAccumulateModify.setAssetsType(Byte.parseByte(AssetsType.ASSETS_SHELL.getId() + ""));
            reqUserAccumulateModify.setReceiver("评价场馆服务加积分");
            reqUserAccumulateModify.setPayReceive("用户id" + reqCommentAdd.getUid());
            userApiRequest.setData(reqUserAccumulateModify);
            APIResponse<RespUserAccumulateModify> respRuleDetailAPIResponse = userAssetsService
                    .modifyAccumulate(userApiRequest);
            logger.debug("===========调用积分系统 userApiRequest:{}", JSON.toJSONString(userApiRequest));
            if (!respRuleDetailAPIResponse.isRet()) {
                logger.error("===========调用积分系统异常");
                logger.debug("===========调用积分系统 respRuleDetailAPIResponse:{}", JSON.toJSONString(respRuleDetailAPIResponse));
                return APIResponse.returnFail("调用资产系统异常！");
            }

//            // 增加索引
//            try{
//                TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(reqCommentAdd.getPlaceId());
//                this.searchService.addPlaceIndex(tbBizPlace, null);
//            }catch (Exception e){
//                logger.error("增加索引失败!");
//            }
            //评论后线程更新索引
            try {
                executorService.execute(new SolrIndexThread(reqCommentAdd.getPlaceId(), null, tbBizPlaceMapper, searchService));
            } catch (Exception e) {
                logger.error("增加索引失败!");
            }
            response.setData(Integer.parseInt(Constants.YES + ""));
        } else {
            response.setData(Integer.parseInt(Constants.NO + ""));
        }
        return response;
    }

    private boolean modBizPlace(Double placeScore, Integer id) {
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(id);
        if (StringUtils.isEmpty(id)) {
            return false;
        }
        if(tbBizPlace == null )
            return false;
        int tbCommentCount = 0;
        if (!StringUtils.isEmpty(tbBizPlace.getCommentCount())) {
            tbCommentCount = tbBizPlace.getCommentCount();
        }
        Integer newCommentCount = StringUtils.isEmpty(tbBizPlace.getCommentCount()) ? 1
                : tbBizPlace.getCommentCount() + 1;
        Double newScore = StringUtils.isEmpty(tbBizPlace.getPlaceScore()) ? placeScore
                : (tbBizPlace.getPlaceScore() * tbCommentCount + placeScore) / newCommentCount;
        tbBizPlace.setCommentCount(newCommentCount);
        tbBizPlace.setPlaceScore(newScore);
        Integer flag = tbBizPlaceMapper.updateByPrimaryKeySelective(tbBizPlace);
        return flag != 0;
    }

    @Override
    public APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> collectList(@NotNull(message = "uid不能为空") Integer uid,
                                                                        @NotNull(message = "经度不能为空") double currLng,
                                                                        @NotNull(message = "纬度不能为空") double currLat,
                                                                        Integer pageNum, Integer pageSize) {
        RedisKey rediskey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY, uid + PlaceConstants.USER_COLLECT_REDIS_KEY);
        Object object = this.placeRedisTemplate.hvals(rediskey.getRedisKey());
        List<RespBizPlaceBaseInfo> redisBizPlaceInfos = new ArrayList<RespBizPlaceBaseInfo>();
        if (object != null) {
        	List<RespBizPlaceBaseInfo> countBizPlaceInfos = (List<RespBizPlaceBaseInfo>) object;
            if (!CollectionUtils.isEmpty(countBizPlaceInfos)) {
            	
                for (RespBizPlaceBaseInfo respBizPlaceBaseInfo : countBizPlaceInfos) {
                	if (respBizPlaceBaseInfo != null) {
                		 TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(respBizPlaceBaseInfo.getId());
                         if (null == respBizPlaceBaseInfo.getIsVip() && null != placeAttach){
                             respBizPlaceBaseInfo.setIsVip(placeAttach.getIsVip()!=null ? placeAttach.getIsVip().intValue() : 0);
                         }
                         if (!StringUtils.isEmpty(respBizPlaceBaseInfo)) {
                             //返回收藏的距离
                             respBizPlaceBaseInfo.setDistance(DistanceUtil.getDistance(currLng, currLat, respBizPlaceBaseInfo.getLng(), respBizPlaceBaseInfo.getLat()) * 1000);
                             PlaceUnitSalePlan placeUnitSalePlan = new PlaceUnitSalePlan();
                             //System.out.println(respBizPlaceBaseInfo.getId());

                             placeUnitSalePlan.setPlaceId(respBizPlaceBaseInfo.getId());
                             placeUnitSalePlan.setCategoryId(null);
                             List<TbBizPlaceUnitSalePlan> minPrices = this.placeUnitSalePlanMapper.getBizPlaceMinPrice(placeUnitSalePlan);
                             if (CollectionUtils.isNotEmpty(minPrices)) {
                                 respBizPlaceBaseInfo.setLowestPrice(minPrices.get(0).getPrice().doubleValue());
                             }
                             redisBizPlaceInfos.add(respBizPlaceBaseInfo);
                         }
                	}
                }
            }
        }
        // 判断redis中是否有收藏数据
        if (CollectionUtils.isEmpty(redisBizPlaceInfos)) {
            //没有数据
            ReqUserCollectQuery reqUserCollectQuery = new ReqUserCollectQuery();
            reqUserCollectQuery.setSystemCode(Constants.PLACE_SYSTEM_CODE);
            reqUserCollectQuery.setBusinessCode(Constants.PLACE_BOOKING_CODE);
            reqUserCollectQuery.setUserId(uid);
            reqUserCollectQuery.setPageNum(pageNum);
            reqUserCollectQuery.setPageSize(pageSize);
            /*APIRequest apiRequest = new APIRequest();
            apiRequest.setServicesName(Constants.USERCLIENT_QUERYUSERCOLLECT);
            apiRequest.setRequestData(reqUserCollectQuery);*/
            APIResponse<PageObj<List<RespUserCollect>>> apiResponse = userCollectServiceFacade
                    .queryUserCollect(reqUserCollectQuery);
            if (!apiResponse.isRet()) {
                return APIResponse.returnFail("调用收藏列表服务失败");
            }
            PageObj<List<RespUserCollect>> datas1 = apiResponse.getData();
            if (StringUtils.isEmpty(datas1) && CollectionUtils.isEmpty(datas1.getItems())) {
                logger.debug("=========Uid:{}==========没有收藏列表", uid);
                return APIResponse.returnSuccess(null);
            }
            List<RespBizPlaceBaseInfo> baseInfos = new ArrayList<RespBizPlaceBaseInfo>();
            List<RespUserCollect> datas = datas1.getItems();
            if (CollectionUtils.isEmpty(datas)) {
                logger.debug("=========Uid:{}==========没有收藏列表", uid);
                return APIResponse.returnSuccess(null);
            }
            try {
                for (int i = 0, len = datas.size(); i < len; i++) {
                    RespUserCollect respUserCollect = datas.get(i);
                    Integer placeid = Integer.valueOf(respUserCollect.getBusinessId());

                    RespBizPlaceBaseInfo apiresponse = placeBaseInfoUtils(placeid);
                    if (!StringUtils.isEmpty(apiresponse)) {
                        baseInfos.add(apiresponse);
                        //// TODO: 16/6/22 需要加入mq
                        this.placeRedisTemplate.hset(rediskey.getRedisKey(), placeid + "", apiresponse);
                    }

                }
                PageObj<List<RespBizPlaceBaseInfo>> pageObj = PageObj.create(datas1.getTotal(),
                        pageNum, pageSize, baseInfos);
                baseInfos = this.fenye(redisBizPlaceInfos, pageNum, pageSize);
                pageObj.setItems(baseInfos);
                return APIResponse.returnSuccess(pageObj);
            } catch (Exception e) {
                logger.error("收藏场馆列表:用户ID：{}失败:{}", uid, e);
                return APIResponse.returnFail("收藏场馆列表失败");
            }
        }

//        PageModel0 pageModel0 = new PageModel0(redisBizPlaceInfos, pageSize);
//
//        if (pageNum >= pageModel0.getTotalPages()){
//            return APIResponse.returnSuccess(null);
//        }
//        List<RespBizPlaceBaseInfo> list = pageModel0.getObjects(pageNum);
//        if(CollectionUtils.isEmpty(list)){
//            return APIResponse.returnSuccess(null);
//        }
//        System.out.println(list.size());
        PageObj<List<RespBizPlaceBaseInfo>> pageObj = PageObj.create(redisBizPlaceInfos.size(), pageNum, pageSize, redisBizPlaceInfos);
        redisBizPlaceInfos = this.fenye(redisBizPlaceInfos, pageNum, pageSize);
        pageObj.setItems(redisBizPlaceInfos);
        return APIResponse.returnSuccess(pageObj);
    }

    /**
     * 列表假分页
     *
     * @param list
     * @param pageNum
     * @param pagesize
     * @return
     */
    public List fenye(List list, int pageNum, int pagesize) {
        int totalcount = list.size();
        int pagecount = 0;
        int m = totalcount % pagesize;
        if (m > 0) {
            pagecount = totalcount / pagesize + 1;
        } else {
            pagecount = totalcount / pagesize;
        }
        List tempList = new ArrayList();
        for (int i = 1; i <= pagecount; i++) {
            if (m == 0) {
                List<Integer> subList = list.subList((i - 1) * pagesize, pagesize * (i));
                tempList.add(subList);
            } else {
                if (i == pagecount) {
                    List<Integer> subList = list.subList((i - 1) * pagesize, totalcount);
                    tempList.add(subList);
                } else {
                    List<Integer> subList = list.subList((i - 1) * pagesize, pagesize * (i));
                    tempList.add(subList);
                }
            }
        }

        try {
            tempList = (List) tempList.get(pageNum);
        } catch (IndexOutOfBoundsException e) {
            logger.error("列表分页出错:{}", JSON.toJSONString(list));
            return null;
        }
        return tempList;
    }

    @Override
    public APIResponse<Integer> collect(@NotNull(message = "uid不能为空") Integer uid,
                                        @NotNull(message = "placeId不能为空") Integer placeId,
                                        @NotNull(message = "type不能为空") Integer type) {
        ReqUserCollect reqUserCollect = new ReqUserCollect();
        reqUserCollect.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        reqUserCollect.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqUserCollect.setUserId(uid);
        reqUserCollect.setBusinessId(placeId);
        reqUserCollect.setStatus(type);

        APIResponse<?> apiResponse;
        if (type.intValue() == Constants.YES) {
            apiResponse = userCollectServiceFacade.userCollect(reqUserCollect);
        } else {
            apiResponse = userCollectServiceFacade.cancleUserCollect(reqUserCollect);
        }

        if (!apiResponse.isRet()) {
            return APIResponse.returnFail("调用收藏取消服务失败");
        }
        APIResponse<Integer> response = new APIResponse<>();
        BeanUtils.copyProperties(apiResponse, response);

        if (apiResponse.getErrcode() != ApiResponseEnum.SUCCESS.getId()) {
            response.setData(Integer.parseInt(Constants.NO + ""));
        }
        if (apiResponse.getErrcode() == ApiResponseEnum.SUCCESS.getId()) {
            response.setData(Integer.parseInt(Constants.YES + ""));
            // 增加/取消收藏场馆放redis
            RedisKey rediskey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY, uid + PlaceConstants.USER_COLLECT_REDIS_KEY);
            RespBizPlaceBaseInfo respBizPlaceBaseInfo = this.placeBaseInfoUtils(placeId);
            if (!StringUtils.isEmpty(respBizPlaceBaseInfo)) {
                if (type.intValue() == Constants.YES) {
                    this.placeRedisTemplate.hset(rediskey.getRedisKey(), placeId + "", respBizPlaceBaseInfo);
                } else {
                    this.placeRedisTemplate.hdel(rediskey.getRedisKey(), placeId.toString().getBytes());
                }
            }
        }
        return response;
    }


    @Override
    public APIResponse<RespSearchElements> searchElements(Integer clientType, Integer type) {
        //TODO 需要加redis中
        RespSearchElements respSearchElements = new RespSearchElements();
        List<RespCityInfo> respCityInfos = baseService.getSysCityInfo(clientType);
        if (CollectionUtils.isEmpty(respCityInfos)) {
            return APIResponse.returnFail("没有开通的城市");
        }
        respSearchElements.setRespCityInfo(respCityInfos);

        //获取运动项目
        List<RespCategory> respCategories = null;
        RedisKey rediskey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY,
                PlaceConstants.PLACE_ALL_CATEGORIES_REDIS_KEY);
        //缓存取
        respCategories = (List<RespCategory>) redisTemplate.get(rediskey);
        if (CollectionUtils.isEmpty(respCategories)) {
            //缓存没有就查db
            respCategories = baseService.getSysCategroyInfo();
        }
        if (CollectionUtils.isEmpty(respCategories)) {
            return APIResponse.returnFail("没有对应的运动项目");
        }
        //h5 羽毛球第一
        RespCategory respCategoryYmq = new RespCategory();
        respCategoryYmq.setId(2);
        respCategoryYmq.setName("羽毛球");

        RespCategory respCategorylq = new RespCategory();
        respCategorylq.setId(1);
        respCategorylq.setName("篮球");

        RespCategory respCategoryZq = new RespCategory();
        respCategoryZq.setId(3);
        respCategoryZq.setName("足球");

        RespCategory respCategoryWq = new RespCategory();
        respCategoryWq.setId(4);
        respCategoryWq.setName("网球");
        List<RespCategory> respCategoriestmp = new ArrayList<>();
        respCategoriestmp.add(respCategoryYmq);
        respCategoriestmp.add(respCategorylq);
        respCategoriestmp.add(respCategoryZq);
        respCategoriestmp.add(respCategoryWq);
        respSearchElements.setCategory(respCategoriestmp);

        //获取排序字段
        List<RespDict> dicts = searchService.getSearchSort();
        if (CollectionUtils.isEmpty(dicts)) {
            return APIResponse.returnFail("没有可选择的排序要素");
        }
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer) httpServletRequest.getAttribute("uid");
        if ((!StringUtils.isEmpty(type) && type.intValue() == 1) || StringUtils.isEmpty(userId) || userId == 0) {
//            dicts.remove(0);
            for(RespDict dict : dicts){
                if("订场历史".equals(dict.getName())){
                    dicts.remove(dict);
                    break;
                }
            }
        }

        respSearchElements.setSortMethod(dicts);
        respSearchElements.setCurrentTime(new Date().getTime());
        return APIResponse.returnSuccess(respSearchElements);
    }

    @Override
    public APIResponse<RespBizPlaceBaseInfo> placeBaseInfo(Integer placeId) {
        RespBizPlaceBaseInfo respBizPlaceBaseInfo = placeBaseInfoUtils(placeId);
        if (respBizPlaceBaseInfo == null) {
            return APIResponse.returnFail("场馆不存在！");
        }
        return APIResponse.returnSuccess(respBizPlaceBaseInfo);
    }

    public RespBizPlaceBaseInfo placeBaseInfoUtils(Integer placeId, ReqSearchVo reqSearchVo) {
        RespBizPlaceBaseInfo respBizPlaceBaseInfo = new RespBizPlaceBaseInfo();
        //获取场馆基本信息
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeId);
        if (tbBizPlace == null) {
            return null;
        }

        //获取场馆图片信息
        TbPlaceImageExample tbPlaceImageExample = new TbPlaceImageExample();
        TbPlaceImageExample.Criteria tbPlaceImageCriteria = tbPlaceImageExample.createCriteria();
        tbPlaceImageCriteria.andTopicIdEqualTo(placeId);
        List<TbPlaceImage> tbPlaceImageList = tbPlaceImageMapper.selectUrlByExample(tbPlaceImageExample);

        //获取场馆运动类别信息
        TbBizPlaceCategoryExample tbBizPlaceCategoryExample = new TbBizPlaceCategoryExample();
        TbBizPlaceCategoryExample.Criteria tbBizPlaceCategoryCriteria = tbBizPlaceCategoryExample.createCriteria();
        tbBizPlaceCategoryCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceCategory> tbBizPlaceCategoryList = tbBizPlaceCategoryMapper
                .selectByExample(tbBizPlaceCategoryExample);
        List<RespCategory> categorys = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(tbBizPlaceCategoryList)) {
            for (TbBizPlaceCategory tbBizPlaceCategory : tbBizPlaceCategoryList) {
                RespCategory respCategory = new RespCategory();
                respCategory.setId(tbBizPlaceCategory.getCategoryId());
                respCategory.setName(baseService.getCommonDataCache("cagetory"
                        + tbBizPlaceCategory.getCategoryId().toString()));
                if (tbBizPlaceCategory.getCategoryId().equals(reqSearchVo.getCategoryId())) {
                    categorys.add(0, respCategory);
                } else {
                    categorys.add(respCategory);
                }
            }
            respBizPlaceBaseInfo.setCategorys(categorys);

        }

        //获取场馆城市信息
        TbCity tbCity = tbCityMapper.selectByPrimaryKey(tbBizPlace.getCityId());
        //获取场馆区域信息
        TbDistrict tbDistrict = tbDistrictMapper.selectByPrimaryKey(tbBizPlace.getDistrictId());
        //签约isSign为null置为0
        if (tbBizPlace.getIsSign() == null) {
            respBizPlaceBaseInfo.setIsSign(PlaceConstants.IS_SIGN_NO);
        }
        try {
            BeanUtils.copyProperties(tbBizPlace, respBizPlaceBaseInfo);
            //数据库搜索计算返回距离
            if (!StringUtils.isEmpty(reqSearchVo.getLng()) && !StringUtils.isEmpty(reqSearchVo.getLat())) {
                respBizPlaceBaseInfo.setDistance(DistanceUtil.getDistance(tbBizPlace.getLng(),
                        tbBizPlace.getLat(), reqSearchVo.getLng(), reqSearchVo.getLat()) * 1000);
            }
            //最低价
            Map<Integer, Double> map = getLPrice(tbBizPlace.getId());
            if (!StringUtils.isEmpty(map)) {
                respBizPlaceBaseInfo.setLowestPrice(map.get(reqSearchVo.getCategoryId()));
            }
            List<RespImage> respImageList = new ArrayList<>();
            for (TbPlaceImage tbPlaceImage : tbPlaceImageList) {
                RespImage respImage = new RespImage();
                BeanUtils.copyProperties(tbPlaceImage, respImage);
                respImageList.add(respImage);
            }
            respBizPlaceBaseInfo.setImages(respImageList);

            RespCity respCity = new RespCity();
            BeanUtils.copyProperties(tbCity, respCity);
            respBizPlaceBaseInfo.setCityObj(respCity);

            RespDistrict respDistrict = new RespDistrict();
            BeanUtils.copyProperties(tbDistrict, respDistrict);
            respBizPlaceBaseInfo.setDistrictObj(respDistrict);

            TbBizPlaceAttach placeAttach = this.getBizPlaceAttach(placeId);
            if (null != placeAttach && null != placeAttach.getIsVip()){
                respBizPlaceBaseInfo.setIsVip(placeAttach.getIsVip().intValue());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return respBizPlaceBaseInfo;
    }

    /**
     * 根据场馆ID获取场馆附属信息
     *
     * @param placeId
     * @return
     */
    public TbBizPlaceAttach getBizPlaceAttach(Integer placeId) {
        TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
        TbBizPlaceAttachExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
        }
        List<TbBizPlaceAttach> result = tbBizPlaceAttachMapper.selectByExample(example);
        if (result != null && result.size() > 0) {
            return result.get(0);
        } else {
            return null;
        }
    }

    public Map<Integer, Double> getLPrice(Integer placeId) {
        PlaceUnitSalePlan placeUnitSalePlan = new PlaceUnitSalePlan();
        placeUnitSalePlan.setPlaceId(placeId);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlenList = placeUnitSalePlanMapper
                .getBizPlaceMinPrice(placeUnitSalePlan);
        if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlenList)) {
            Map<Integer, Double> prices = new HashMap<>();
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlenList) {
                if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan.getPrice())) {
                    prices.put(tbBizPlaceUnitSalePlan.getCategoryId(), tbBizPlaceUnitSalePlan.getPrice().doubleValue());
                }
            }
            return prices;
        }
        return null;
    }

    public RespBizPlaceBaseInfo placeBaseInfoUtils(Integer placeId) {
        RespBizPlaceBaseInfo respBizPlaceBaseInfo = new RespBizPlaceBaseInfo();
        //获取场馆基本信息
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeId);
        if (tbBizPlace == null) {
            return null;
        }

        //获取场馆图片信息
        TbPlaceImageExample tbPlaceImageExample = new TbPlaceImageExample();
        TbPlaceImageExample.Criteria tbPlaceImageCriteria = tbPlaceImageExample.createCriteria();
        tbPlaceImageCriteria.andTopicIdEqualTo(placeId);
        List<TbPlaceImage> tbPlaceImageList = tbPlaceImageMapper.selectUrlByExample(tbPlaceImageExample);

        //获取场馆运动类别信息
        TbBizPlaceCategoryExample tbBizPlaceCategoryExample = new TbBizPlaceCategoryExample();
        TbBizPlaceCategoryExample.Criteria tbBizPlaceCategoryCriteria = tbBizPlaceCategoryExample.createCriteria();
        tbBizPlaceCategoryCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceCategory> tbBizPlaceCategoryList = tbBizPlaceCategoryMapper
                .selectByExample(tbBizPlaceCategoryExample);
        List<RespCategory> categorys = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(tbBizPlaceCategoryList)) {
            for (TbBizPlaceCategory tbBizPlaceCategory : tbBizPlaceCategoryList) {
                RespCategory respCategory = new RespCategory();
                respCategory.setId(tbBizPlaceCategory.getCategoryId());
                respCategory.setName(baseService.getCommonDataCache("cagetory"
                        + tbBizPlaceCategory.getCategoryId().toString()));
                categorys.add(respCategory);
            }
            respBizPlaceBaseInfo.setCategorys(categorys);

        }

        //获取场馆城市信息
        TbCity tbCity = tbCityMapper.selectByPrimaryKey(tbBizPlace.getCityId());
        //获取场馆区域信息
        TbDistrict tbDistrict = tbDistrictMapper.selectByPrimaryKey(tbBizPlace.getDistrictId());
        //签约isSign为null置为0
        if (tbBizPlace.getIsSign() != null) {
            respBizPlaceBaseInfo.setIsSign(tbBizPlace.getIsSign());
        } else {
            respBizPlaceBaseInfo.setIsSign(PlaceConstants.IS_SIGN_NO);
        }
        try {
            BeanUtils.copyProperties(tbBizPlace, respBizPlaceBaseInfo);
            TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlace.getId());
            if (null != placeAttach){
                respBizPlaceBaseInfo.setIsVip(placeAttach.getIsVip().intValue());
            }
            if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
                respBizPlaceBaseInfo.setPhone(placeAttach.getBookingConsultPhone());
            } else {
                // 获取系统配置的百灵鸟客服热线
                TbCommonParameter parameterVo = baseServiceimpl.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                if (null != parameterVo){
                    respBizPlaceBaseInfo.setPhone(parameterVo.getParameterValue());
                }
            }

            List<RespImage> respImageList = new ArrayList<>();
            List<RespVideo> respVideoList = new ArrayList<>();
            for (TbPlaceImage tbPlaceImage : tbPlaceImageList) {
                if (PlaceConstants.PLACE_CONTENT_TYPE_IMAGE.equals(tbPlaceImage.getContentType())) {
                    RespImage respImage = new RespImage();
                    BeanUtils.copyProperties(tbPlaceImage, respImage);
                    respImageList.add(respImage);
                } else if (PlaceConstants.PLACE_CONTENT_TYPE_VIDEO.equals(tbPlaceImage.getContentType())) {
                    RespVideo respVideo = new RespVideo();
                    BeanUtils.copyProperties(tbPlaceImage, respVideo);
                    respVideoList.add(respVideo);
                    respBizPlaceBaseInfo.setVideoUrl(tbPlaceImage.getUrl());
                }
            }

            respBizPlaceBaseInfo.setVideoUrl(null);//TODO  先返回null，运营如今没有录入视频，以后再放开
            respBizPlaceBaseInfo.setImages(respImageList);
            respBizPlaceBaseInfo.setVideos(respVideoList);
            RespCity respCity = new RespCity();
            BeanUtils.copyProperties(tbCity, respCity);
            respBizPlaceBaseInfo.setCityObj(respCity);

            RespDistrict respDistrict = new RespDistrict();
            BeanUtils.copyProperties(tbDistrict, respDistrict);
            respBizPlaceBaseInfo.setDistrictObj(respDistrict);
            respBizPlaceBaseInfo.setIsShelves(tbBizPlace.getIsShelves());
            respBizPlaceBaseInfo.setCommentCount(getCommentCount(placeId));//TODO
            respBizPlaceBaseInfo.setBusinessMode(tbBizPlace.getBusinessMode());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return respBizPlaceBaseInfo;
    }



    private Integer getCommentCount(Integer placeId){
        ReqBaseParam reqBaseParam = new ReqBaseParam();
        reqBaseParam.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqBaseParam.setBusinessId(placeId);
        reqBaseParam.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        RespCommentSum respCommentSum = commentServiceFacade.queryCommentSum(reqBaseParam);
        if (null != respCommentSum.getCommentCount()){
            return respCommentSum.getCommentCount();
        }
        return 0;
    }

    @Override
    public APIResponse<RespPlaceUnitSalePlanDetail> placeSalePlan(ReqPlaceSalePlan reqPlaceSalePlan) {
        RespPlaceUnitSalePlanDetail respPlaceUnitSalePlanDetail = placeSalePlanUtils(reqPlaceSalePlan);
        if (null != respPlaceUnitSalePlanDetail) {
            return APIResponse.returnSuccess(respPlaceUnitSalePlanDetail);
        }
        return APIResponse.returnFail("不存在这天的销售计划！");
    }

    public RespPlaceUnitSalePlanDetail placeSalePlanUtils(ReqPlaceSalePlan reqPlaceSalePlan) {
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer) httpServletRequest.getAttribute("uid");
        if (userId != null && userId > 0) {
            reqPlaceSalePlan.setUid(userId);
        } else {
            reqPlaceSalePlan.setUid(0);
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("get sale plan list");
        RespPlaceUnitSalePlanDetail placeUnitSalePlanDetail = new RespPlaceUnitSalePlanDetail();
        placeUnitSalePlanDetail.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        placeUnitSalePlanDetail.setSystemCode(Constants.PLACE_SYSTEM_CODE);

        List<RespPlaceUnitSalePlanByDay> placeUnitInfoVoList = new ArrayList<>();
        Date currDate = new Date(System.currentTimeMillis() - 60 * 60 * 1000);//当前时间前一小时
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria tbBizPlaceUnitSalePlanCriteria =
                tbBizPlaceUnitSalePlanExample.createCriteria();
        tbBizPlaceUnitSalePlanCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
        tbBizPlaceUnitSalePlanCriteria.andCategoryIdEqualTo(reqPlaceSalePlan.getCategoryId());
        Date startDate = DateUtils.transferLongToDate(reqPlaceSalePlan.getStartDate());
        Date endDate = DateUtils.transferLongToDate(reqPlaceSalePlan.getEndDate());
        if (reqPlaceSalePlan.getStartDate().equals(reqPlaceSalePlan.getEndDate())) {
            tbBizPlaceUnitSalePlanCriteria.andDateEqualTo(startDate);
        } else {
            tbBizPlaceUnitSalePlanCriteria.andDateBetween(startDate, endDate);
        }

        tbBizPlaceUnitSalePlanCriteria.andIsEffectiveEqualTo(Constants.YES);
        tbBizPlaceUnitSalePlanCriteria.andUnitTypeEqualTo(PlaceConstants.UNIT_TYPE_BASE);      // 只选择基本场馆
        tbBizPlaceUnitSalePlanExample.setOrderByClause("place_unit_name,start_time");//按照场地名称排序，+0将MySQL字符串字段按数值排序

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanMapper
                .selectByExample(tbBizPlaceUnitSalePlanExample);


        Map<String, RespPlaceUnitSalePlanByDay> respPlaceUnitSalePlanByDayMap = new HashMap<>();
        Map<String, RespPlaceUnitInfoVo> respPlaceUnitInfoVoMap = new HashMap<>();
        Set<Integer> expiredBundleNoSet = new TreeSet<>();
        Set<Integer> orderBundleNoSet = new TreeSet<>();
        //String earlyStartTime = null;  //最早的营业时间
        //String lateEndTime = null;   //最晚的营业时间
        if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanList)) {
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
                String date = DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate());
                if (!respPlaceUnitSalePlanByDayMap.containsKey(date)) {//根据date区分RespPlaceUnitSalePlanByDay
                    RespPlaceUnitSalePlanByDay respPlaceUnitSalePlanByDay = new RespPlaceUnitSalePlanByDay();
                    respPlaceUnitSalePlanByDay.setDate(date);
                    respPlaceUnitSalePlanByDay.setWeek(DateUtils.dayForWeek(date));
                    respPlaceUnitSalePlanByDayMap.put(date, respPlaceUnitSalePlanByDay);
                    placeUnitInfoVoList.add(respPlaceUnitSalePlanByDay);
                }
                RespPlaceUnitSalePlanByDay respPlaceUnitSalePlanByDay = respPlaceUnitSalePlanByDayMap.get(date);

                if (CollectionUtils.isEmpty(respPlaceUnitSalePlanByDay.getPlaceUnitList())) {
                    List<RespPlaceUnitInfoVo> respPlaceUnitInfoVoList = new ArrayList<>();
                    respPlaceUnitSalePlanByDay.setPlaceUnitList(respPlaceUnitInfoVoList);
                }

                List<RespPlaceUnitInfoVo> respPlaceUnitInfoVoList = respPlaceUnitSalePlanByDay.getPlaceUnitList();

                if (!respPlaceUnitInfoVoMap.containsKey(date + tbBizPlaceUnitSalePlan.getPlaceUnitId())) {
                    RespPlaceUnitInfoVo respPlaceUnitInfoVo = new RespPlaceUnitInfoVo();
                    RespPlaceUnitInfo respPlaceUnitInfo = new RespPlaceUnitInfo();
                    respPlaceUnitInfo.setId(tbBizPlaceUnitSalePlan.getPlaceUnitId());
                    respPlaceUnitInfo.setName(tbBizPlaceUnitSalePlan.getPlaceUnitName());// TODO 从数据库获取场地详情

                    respPlaceUnitInfoVo.setRespPlaceUnitInfo(respPlaceUnitInfo);
                    respPlaceUnitInfoVoMap.put(date + tbBizPlaceUnitSalePlan.getPlaceUnitId(), respPlaceUnitInfoVo);

                    respPlaceUnitInfoVoList.add(respPlaceUnitInfoVo);
                }
                RespPlaceUnitInfoVo respPlaceUnitInfoVo = respPlaceUnitInfoVoMap
                        .get(date + tbBizPlaceUnitSalePlan.getPlaceUnitId());

                if (CollectionUtils.isEmpty(respPlaceUnitInfoVo.getPlaceUnitSalePlanList())) {
                    List<RespPlaceUnitSalePlanVo> placeUnitSalePlanList = new ArrayList<>();
                    respPlaceUnitInfoVo.setPlaceUnitSalePlanList(placeUnitSalePlanList);

                }

                List<RespPlaceUnitSalePlanVo> placeUnitSalePlanList = respPlaceUnitInfoVo.getPlaceUnitSalePlanList();


                RespPlaceUnitSalePlanVo respPlaceUnitSalePlanVo = new RespPlaceUnitSalePlanVo();
                RespPlaceUnitSalePlan respPlaceUnitSalePlan = new RespPlaceUnitSalePlan();
                if (PlaceConstants.PLACE_ORDER_STATUS.equals(tbBizPlaceUnitSalePlan.getStatus())
                        && PlaceConstants.YES.equals(reqPlaceSalePlan.getIsNeedUserInfo())) {
                    //查询新的用户系统
                    APIResponse<RespUserInfoBase> result = userServiceFacade
                            .queryUserInfo(tbBizPlaceUnitSalePlan.getOrderUid());
                    //旧系统的查询用户信息接口
                    //APIResponse<User> result = userService.userInfo(tbBizPlaceUnitSalePlan.getOrderUid());
                    RespPlaceUserInfo userInfo = new RespPlaceUserInfo();
                    if (result.isRet()) {
                        try {
                            BeanUtils.copyProperties(result.getData(), userInfo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    RespBizPlaceSalePlanOrderInfo orderInfo = new RespBizPlaceSalePlanOrderInfo();
                    //获取订单时间
                    TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
                    tbBizPlaceOrderItemExample.createCriteria().andUnitSalePlanIdEqualTo(tbBizPlaceUnitSalePlan.getId());
                    List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this
                            .tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
                    if (CollectionUtils.isNotEmpty(tbBizPlaceOrderItems)) {
                        orderInfo.setOrderTime(tbBizPlaceOrderItems.get(0).getCreateTime().getTime());
                        orderInfo.setOrderNo(tbBizPlaceOrderItems.get(0).getPlaceOrderId());
                    }
                    orderInfo.setUserInfo(userInfo);
                    respPlaceUnitSalePlanVo.setOrderInfo(orderInfo);
                }

                /*String startTime = DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime());
                String endTime = DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime());
                if (null == earlyStartTime) {
                    earlyStartTime = startTime;
                } else {
                    if (startTime.compareTo(earlyStartTime) <= 0) {
                        earlyStartTime = startTime;
                    }
                }

                if (null == lateEndTime) {
                    lateEndTime = endTime;
                } else {
                    if (endTime.compareTo(lateEndTime) >= 0) {
                        lateEndTime = endTime;
                    }
                }

                respPlaceUnitSalePlan.setStartTime(startTime);
                respPlaceUnitSalePlan.setEndTime(endTime);*/
                respPlaceUnitSalePlan.setStartTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()));
                respPlaceUnitSalePlan.setEndTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()));

                respPlaceUnitSalePlan.setPlaceId(tbBizPlaceUnitSalePlan.getPlaceId());
                respPlaceUnitSalePlan.setPlaceUnitId(tbBizPlaceUnitSalePlan.getPlaceUnitId());
                respPlaceUnitSalePlan.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
                respPlaceUnitSalePlan.setPrice(tbBizPlaceUnitSalePlan.getPrice());
                String salePlanDateString = DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate());
                //Date salePlanDate = DateUtils.dateStrToDate(salePlanDateString + " " + startTime + ":00");
                Date salePlanDate = DateUtils.dateStrToDate(salePlanDateString + " " + respPlaceUnitSalePlan.getStartTime() + ":00");
                if (tbBizPlaceUnitSalePlan.getBundleNo() == null) {
                    tbBizPlaceUnitSalePlan.setBundleNo(0);
                }
                //如果销售计划开始时间大于当前系统时间，设置为原始状态，否则设置为已售状态
                if (salePlanDate != null && salePlanDate.before(currDate)) {
                    respPlaceUnitSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);//预定状态
                    if (!tbBizPlaceUnitSalePlan.getBundleNo().equals(0)) {
                        expiredBundleNoSet.add(tbBizPlaceUnitSalePlan.getBundleNo());
                    }

                } else {
                    respPlaceUnitSalePlan.setStatus(tbBizPlaceUnitSalePlan.getStatus());
                }

                //如果捆绑组其中一个时段已经售出，该捆绑组全部都不能卖（商家端可以卖），存入orderBundleNoSet集合中，后续会处理
                if (!PlaceConstants.PLACE_PREORDER_STATUS.equals(tbBizPlaceUnitSalePlan.getStatus())) {
                    if (!tbBizPlaceUnitSalePlan.getBundleNo().equals(0)) {
                        orderBundleNoSet.add(tbBizPlaceUnitSalePlan.getBundleNo()+tbBizPlaceUnitSalePlan.getPlaceUnitId());
                    }
                }

                //同一组的销售计划开始时间过期，则这一组都设置为过期数据
                if (expiredBundleNoSet.contains(tbBizPlaceUnitSalePlan.getBundleNo())) {
                    respPlaceUnitSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);//预定状态
                }

                respPlaceUnitSalePlan.setDate(DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate()));
                respPlaceUnitSalePlan.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
                respPlaceUnitSalePlan.setLowestPrice(tbBizPlaceUnitSalePlan.getLowestPrice());
                respPlaceUnitSalePlan.setBundleNo(tbBizPlaceUnitSalePlan.getBundleNo());
                respPlaceUnitSalePlanVo.setRespPlaceUnitSalePlan(respPlaceUnitSalePlan);
                placeUnitSalePlanList.add(respPlaceUnitSalePlanVo);
            }

        }


        placeUnitSalePlanDetail.setPlaceUnitInfoVoList(placeUnitInfoVoList);
        stopWatch.stop();

        stopWatch.start("get place info");
        RespBizPlaceBaseInfo respBizPlaceBaseInfo = placeBaseInfoUtils(reqPlaceSalePlan.getPlaceId());
        if (respBizPlaceBaseInfo == null) {
            return null;
        }
        setPlaceInfoBySalePlan(placeUnitSalePlanDetail, respBizPlaceBaseInfo, reqPlaceSalePlan,
                null, null, orderBundleNoSet);
        stopWatch.stop();
        logger.info(stopWatch.prettyPrint());
        return placeUnitSalePlanDetail;
    }

    @Override
    public APIResponse<RespPlaceUnitSalePlanDetail> placeCombineSalePlan(ReqPlaceSalePlan reqPlaceSalePlan) {
        RespPlaceUnitSalePlanDetail respPlaceUnitSalePlanDetail = placeSalePlanUtils(reqPlaceSalePlan);
        if (respPlaceUnitSalePlanDetail == null) {
            return APIResponse.returnFail("不存在这天的销售计划！");
        }

        // 只有篮球和足球有组合场的概念
        Integer cateId = reqPlaceSalePlan.getCategoryId();
        if (cateId.equals(1)    /*篮球(注意篮球暂时还未录入场地规模数据暂时先放这里)*/
            || cateId.equals(2) /*羽毛球*/
            || cateId.equals(4) /*网球*/) {
            return APIResponse.returnSuccess(respPlaceUnitSalePlanDetail);
        }

        String fieldScale = reqPlaceSalePlan.getFieldScale();
        if (fieldScale == null) {
            return APIResponse.returnFail("请指定场地规模！");
        }

        // 将销售计划按场地组合重组后返回
        return placeUCService.combinePlaceUnit(reqPlaceSalePlan.getPlaceId(), reqPlaceSalePlan.getCategoryId(), reqPlaceSalePlan.getFieldScale(),
                reqPlaceSalePlan.getStartDate(), reqPlaceSalePlan.getEndDate(), respPlaceUnitSalePlanDetail);
    }

    @Override
    public APIResponse<RespBizPlaceDetailInfo> placeDetailInfo(ReqPlaceDetailInfo reqPlaceDetailInfo) {
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer) httpServletRequest.getAttribute("uid");
        reqPlaceDetailInfo.setUid(userId);
        Integer placeId = reqPlaceDetailInfo.getPlaceId();
        Integer uid = reqPlaceDetailInfo.getUid();
        Integer categoryId = reqPlaceDetailInfo.getCategoryId();
        RespBizPlaceDetailInfo respBizPlaceDetailInfo = new RespBizPlaceDetailInfo();
        //获取场馆基本信息
        RespBizPlaceBaseInfo respBizPlaceBaseInfo = placeBaseInfoUtils(placeId);
        if (respBizPlaceBaseInfo == null) {
            return APIResponse.returnFail("不存在该场馆信息！");
        }

        if (uid != null) {
            boolean isCollect = isCollect(uid, placeId);
            if (isCollect) {
                respBizPlaceBaseInfo.setIsCollect(Constants.NO);
            } else {
                respBizPlaceBaseInfo.setIsCollect(Constants.YES);
            }

            //获取分享的url，包含用户信息
            APIResponse<RespUserInfoBase> result = null;

            String userToken = (String) placeRedisTemplate.get(PlaceConstants.USER_SHARE_PREFIX + userId);
            if (userToken == null) {
                userToken = UUIDUtils.getUUID();
                placeRedisTemplate.set(PlaceConstants.USER_SHARE_PREFIX + userId, userToken,
                        Constants.SHARE_TOKEN_EXPIRED_TIME);
                placeRedisTemplate.set(userToken, userId, Constants.SHARE_TOKEN_EXPIRED_TIME);
            }
            try {
               /* result = userServiceFacade.queryUserInfo(uid);
                if (result.isRet()) {
                    String nickName = result.getData().getNickName();
                    String icon = result.getData().getIcon();
                    respBizPlaceBaseInfo.setShareUrl(placeOrderShareUrl + "?token=" + userToken +
                            "&nickName=" + nickName + "&icon=" + icon);
                }*/
                respBizPlaceBaseInfo.setShareUrl(placeOrderShareUrl+"?placeId="+placeId);
            } catch (Exception e) {
                logger.warn("获取用户信息异常：{}", e.getMessage());
            }



        }
        if (!StringUtils.isEmpty(categoryId)){
            Map<Integer, Double> map = this.baseService.getLPrice(placeId);
            if (MapUtils.isNotEmpty(map)){
                Double price = map.get(categoryId);
                if(!StringUtils.isEmpty(price)){
                    respBizPlaceBaseInfo.setLowestPrice(price);
                }
            }
        }

        respBizPlaceDetailInfo.setPlaceBaseInfo(respBizPlaceBaseInfo);

        //获取场馆附属信息
        TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
        TbBizPlaceAttachExample.Criteria tbBizPlaceAttachCriteria = example.createCriteria();
        tbBizPlaceAttachCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceAttach> result = tbBizPlaceAttachMapper.selectByExample(example);

        RespBizPlaceAttachInfo placeAttachInfo = new RespBizPlaceAttachInfo();
        if (CollectionUtils.isNotEmpty(result)) {
        	 TbBizPlaceAttach tbBizPlaceAttach = result.get(0);
             RespBizPlaceBaseInfo placeBaseInfo = respBizPlaceDetailInfo.getPlaceBaseInfo();
             if (tbBizPlaceAttach.getIsVip() == null) {
                 tbBizPlaceAttach.setIsVip((byte) 0);
             }
             placeBaseInfo.setIsVip(Integer.valueOf(tbBizPlaceAttach.getIsVip()));

             //获取场馆交通信息
             List<RespBizPlaceTrafficInfo> trafficInfoList = new ArrayList<>();
             String trafficInfoString = tbBizPlaceAttach.getTrafficInfo();
             if (!StringUtils.isEmpty(trafficInfoString)) {
                 String[] trafficInfos = trafficInfoString.split("\\|");
                 for (String trafficInfo : trafficInfos) {
                     String[] trafficInfoStr = trafficInfo.split(":");
                     RespBizPlaceTrafficInfo respBizPlaceTrafficInfo = new RespBizPlaceTrafficInfo();
                     respBizPlaceTrafficInfo.setType(trafficInfoStr[0]);
                     respBizPlaceTrafficInfo.setDescribe(trafficInfoStr[1]);
                     trafficInfoList.add(respBizPlaceTrafficInfo);
                 }
                 respBizPlaceDetailInfo.setTrafficInfoList(trafficInfoList);
             }

             try {
                 BeanUtils.copyProperties(tbBizPlaceAttach, placeAttachInfo);
                 placeAttachInfo.setBusinessDescribe("全年不休"); // TODO  数据库是否要存储
                 if(!StringUtils.isEmpty(tbBizPlaceAttach.getBusinessHourStart())){
                     placeAttachInfo.setBusinessHourStart(tbBizPlaceAttach.getBusinessHourStart().substring(0, tbBizPlaceAttach.getBusinessHourStart().lastIndexOf(":")));
                 }
                 if(!StringUtils.isEmpty(tbBizPlaceAttach.getBusinessHourEnd())){
                     placeAttachInfo.setBusinessHourEnd(tbBizPlaceAttach.getBusinessHourEnd().substring(0, tbBizPlaceAttach.getBusinessHourEnd().lastIndexOf(":")));
                 }
                 respBizPlaceDetailInfo.setPlaceAttachInfo(placeAttachInfo);

             } catch (Exception e) {
                 e.printStackTrace();
             }


             List<RespBizPlaceServiceInfo> bizPlaceServiceInfoList = new ArrayList<>();
             Class cls = tbBizPlaceAttach.getClass();
             Field[] fs = cls.getDeclaredFields();
             try {
                 for (Field f : fs) {
                     f.setAccessible(true); //设置些属性是可以访问的
                     Object val = f.get(tbBizPlaceAttach);//得到此属性的值
                     if (f.getName().startsWith("is") && val != null) {//is开头属性都是场馆服务的属性
                         Byte ss = (Byte) val;
                         if (ss == Constants.YES) {//判断是否拥有该场馆服务，如果存在，从缓存中获取场馆服务对象
                             RespBizPlaceServiceInfo respBizPlaceServiceInfo = getBizPlaceServiceInfo(f.getName());
                             if (respBizPlaceServiceInfo != null) {
                                 bizPlaceServiceInfoList.add(respBizPlaceServiceInfo);
                             }

                         }
                     }
                 }
             } catch (Exception e) {
                 e.printStackTrace();
             }
             placeAttachInfo.setBizPlaceServiceInfoList(bizPlaceServiceInfoList);
		}
        return APIResponse.returnSuccess(respBizPlaceDetailInfo);
    }

    @Override
    public APIResponse<List<RespPlaceCommentInfo>> commentList(ReqCommentList reqCommentList) {
        ReqCommentQuery reqCommentQuery = new ReqCommentQuery();
        reqCommentQuery.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        reqCommentQuery.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqCommentQuery.setBusinessId(reqCommentList.getPlaceId());
        reqCommentQuery.setPageNum(reqCommentList.getPageNum());
        reqCommentQuery.setPageSize(reqCommentList.getPageSize());

        APIResponse<List<RespPlaceCommentInfo>> response = new APIResponse();

        PageObj<List<RespComment>> respCommentdatas = commentServiceFacade.commentQuery(reqCommentQuery).getData();
        if (StringUtils.isEmpty(respCommentdatas) || CollectionUtils.isEmpty(respCommentdatas.getItems())) {
            response.setData(null);
            return response;
        }
        List<RespPlaceCommentInfo> respPlaceCommentInfoList = new ArrayList<RespPlaceCommentInfo>();
        List<RespComment> datas = respCommentdatas.getItems();
        Long sysTime = System.currentTimeMillis();
        for (int i = 0, len = datas.size(); i < len; i++) {
            RespComment respComment = datas.get(i);
            Integer placeid = respComment.getBusinessId();
            RespPlaceCommentInfo respPlaceCommentInfo = new RespPlaceCommentInfo();

            //通过uid得到用户信息
            APIResponse<RespUserInfoDetail> result = userServiceFacade.queryUserInfoDetail(respComment.getFromUser());
            if (result.isRet()) {
                RespPlaceUserInfo respPlaceUserInfo = new RespPlaceUserInfo();
                try {
                    BeanUtils.copyProperties(result.getData(), respPlaceUserInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                respPlaceUserInfo.setLevel(result.getData().getLevelDe());
                respPlaceCommentInfo.setUserInfo(respPlaceUserInfo);
            }

            ReqCommentAdd commentObj = new ReqCommentAdd();
            commentObj.setUid(respComment.getFromUser());
            commentObj.setPlaceId(respComment.getBusinessId());
            commentObj.setAvgSocre(respComment.getScore());
            commentObj.setCommentContent(respComment.getCommentContent());
            commentObj.setReplayId(respComment.getReplayId());
            commentObj.setCommentType(respComment.getCommentType());
            commentObj.setCommentTime(respComment.getCreateTime());

            List<RespPlaceElementsInfo> commentTypeList = new ArrayList<>();
            List<RespCommentDetailScore> respCommentDetailScore = respComment.getLstCommentDetailScore();

            if (CollectionUtils.isNotEmpty(respCommentDetailScore)) {
                for (RespCommentDetailScore commentDetailScore : respCommentDetailScore) {
                    RespPlaceElementsInfo respPlaceElementsInfo = new RespPlaceElementsInfo();
                    respPlaceElementsInfo.setId(commentDetailScore.getCommentDetailScoreId());
                    respPlaceElementsInfo.setName(commentDetailScore.getCommentDetailName());
                    respPlaceElementsInfo.setScore(commentDetailScore.getCommentDetailScore());
                    commentTypeList.add(respPlaceElementsInfo);
                }
            }
            commentObj.setCommentTypeList(commentTypeList);
            respPlaceCommentInfo.setCommentObj(commentObj);
            respPlaceCommentInfo.setSysTime(sysTime);

            respPlaceCommentInfoList.add(respPlaceCommentInfo);

        }
        response.setData(respPlaceCommentInfoList);
        return response;
    }

    @Override
    public APIResponse<?> getRespPlaceUnitSalePlanDetail(ReqPlaceSalePlan reqPlaceSalePlan) {
        if (!StringUtils.isEmpty(reqPlaceSalePlan.getWeeks())) {
            String[] ids1 = org.apache.commons.lang3.StringUtils.split(reqPlaceSalePlan.getWeeks(), ",");
            List<String> list = Arrays.asList(ids1);
            List<Integer> weekList = new ArrayList<>();
            for (String weekstr : list) {
                weekList.add(Integer.parseInt(weekstr));
            }
            reqPlaceSalePlan.setWeek(weekList);
        }
        List<TbBizPlaceUnitSalePlan> resultList = new ArrayList<>();
        if (!StringUtils.isEmpty(reqPlaceSalePlan.getFrom()) &&
                reqPlaceSalePlan.getFrom().intValue() == PlaceConstants.PRIVATE_USE_TYPE
                && !StringUtils.isEmpty(reqPlaceSalePlan.getEndDate())) {
            logger.debug("====================开始增加销售计划");
            //包场增加销售计划
            Date startDate = new Date(reqPlaceSalePlan.getStartDate());
            Date endDate = new Date(reqPlaceSalePlan.getEndDate());

            //获取日期内符合星期的销售列表
            List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = getTbBizPlaceUnitSalePlan(reqPlaceSalePlan,
                    startDate, endDate);
            if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
                return APIResponse.returnFail("选择的星期不在日期范围内");
            }

            //获取销售计划模板
            List<String> types = new ArrayList<>();
            for (Integer type : reqPlaceSalePlan.getWeek()) {
                types.add(type + "");
            }
            TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
            TbBizPlaceUnitSalePlanMainExample.Criteria mainCriteria = tbBizPlaceUnitSalePlanMainExample.createCriteria();
            mainCriteria.andIsEffectiveEqualTo(Constants.IS_ENABLE_TRUE).andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId())
                    .andCategoryIdEqualTo(reqPlaceSalePlan.getCategoryId()).andTimeTypeIn(types).andUnitTypeEqualTo((byte)0);
            List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMains = tbBizPlaceUnitSalePlanMainMapper
                    .selectByExample(tbBizPlaceUnitSalePlanMainExample);
            if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMains)) {
                logger.error("==========================没有销售计划模板 ReqPlaceSalePlan:{}",
                        JSON.toJSONString(reqPlaceSalePlan));
                RespBizCodeInfo respBizCodeInfo = new RespBizCodeInfo();
                respBizCodeInfo.setSuccess(false);
                respBizCodeInfo.setGetCode(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getCode());
                respBizCodeInfo.setGetId(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getId());
                respBizCodeInfo.setGetLabel(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getLabel());
                return APIResponse.returnSuccess(respBizCodeInfo);
            }


            for (TbBizPlaceUnitSalePlan tbUnitSalePlan1 : tbBizPlaceUnitSalePlans) {
                //// TODO: 16/6/21 未完成 不判断是否到期
                for (TbBizPlaceUnitSalePlanMain tbMain : tbBizPlaceUnitSalePlanMains) {
                    //去除销售计划模板中没有的数据
                    if (!tbUnitSalePlan1.getTimeType().equals(tbMain.getTimeType())) {
                        continue;
                    }
                    TbBizPlaceUnitSalePlan tbUnitSalePlan = new TbBizPlaceUnitSalePlan();
                    BeanUtils.copyProperties(tbUnitSalePlan1, tbUnitSalePlan);
                    tbUnitSalePlan.setPlaceId(tbMain.getPlaceId());
                    tbUnitSalePlan.setPlaceUnitId(tbMain.getPlaceUnitId());
                    tbUnitSalePlan.setCategoryId(tbMain.getCategoryId());
                    tbUnitSalePlan.setSalePlanMainId(tbMain.getId());
                    tbUnitSalePlan.setSaleId(CommonUtils.createSaleID(tbMain.getPlaceUnitId(), tbUnitSalePlan1.getDate(), tbMain.getStartTime(),tbMain.getEndTime()));       // getTbBizPlaceUnitSalePlan不是从数据库中读取的,此处拼接
                    tbUnitSalePlan.setPlaceUnitName(tbMain.getPlaceUnitName());
                    tbUnitSalePlan.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                    tbUnitSalePlan.setStartTime(tbMain.getStartTime());
                    tbUnitSalePlan.setEndTime(tbMain.getEndTime());
                    tbUnitSalePlan.setPrice(tbMain.getPrice());
                    tbUnitSalePlan.setMemberPrice(tbMain.getMemberPrice());
                    tbUnitSalePlan.setIsEffective(Constants.IS_ENABLE_TRUE);
                    if (tbMain.getBundleNo() != null){
                        if (tbMain.getBundleNo() == 0){
                            tbUnitSalePlan.setBundleNo(0);
                        } else {
                            String bundleNo = tbMain.getPlaceUnitId()+""+tbMain.getBundleNo();
                            tbUnitSalePlan.setBundleNo(Integer.valueOf(bundleNo));
                        }
                    }

                    tbUnitSalePlan.setUnitType(tbMain.getUnitType());  // 从模板中获取场地类型

                    if (PlaceConstants.UNIT_TYPE_COMBINE.equals(tbMain.getUnitType())) {
                        continue; // 商家端暂时不要处理组合场地的情况
                    }

                    resultList.add(tbUnitSalePlan);
                    //break;
                }
            }

//            saveTbUnitSalePlan(resultList);
//              addTbUnitSalePlan(resultList);
        } else if (!StringUtils.isEmpty(reqPlaceSalePlan.getFrom()) &&
                reqPlaceSalePlan.getFrom().intValue() == PlaceConstants.BILLING_TYPE
                && !StringUtils.isEmpty(reqPlaceSalePlan.getStartDate())) {
            //开单加销售计划
            Date startDate = new Date(reqPlaceSalePlan.getStartDate());
            //当前周几
            Integer week = DateUtils.getDayOfWeek(startDate);

            TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
            TbBizPlaceUnitSalePlanMainExample.Criteria mainCriteria = tbBizPlaceUnitSalePlanMainExample.createCriteria();
            mainCriteria.andIsEffectiveEqualTo(Constants.IS_ENABLE_TRUE).andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId())
                    .andCategoryIdEqualTo(reqPlaceSalePlan.getCategoryId()).andTimeTypeEqualTo(week.toString())
                    .andUnitTypeEqualTo((byte)0);
            List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMains = tbBizPlaceUnitSalePlanMainMapper
                    .selectByExample(tbBizPlaceUnitSalePlanMainExample);
            if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMains)) {
                RespBizCodeInfo respBizCodeInfo = new RespBizCodeInfo();
                respBizCodeInfo.setSuccess(false);
                respBizCodeInfo.setGetCode(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getCode());
                respBizCodeInfo.setGetId(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getId());
                respBizCodeInfo.setGetLabel(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getLabel());
                return APIResponse.returnSuccess(respBizCodeInfo);
            }

            for (TbBizPlaceUnitSalePlanMain tbMain : tbBizPlaceUnitSalePlanMains) {
                //去除销售计划模板中没有的数据
                if (!week.toString().equals(tbMain.getTimeType())) {
                    continue;
                }
                TbBizPlaceUnitSalePlan tbUnitSalePlan = new TbBizPlaceUnitSalePlan();
                tbUnitSalePlan.setDate(startDate);
                tbUnitSalePlan.setTimeType(week.toString());
                tbUnitSalePlan.setPlaceId(tbMain.getPlaceId());
                tbUnitSalePlan.setPlaceUnitId(tbMain.getPlaceUnitId());
                tbUnitSalePlan.setCategoryId(tbMain.getCategoryId());
                tbUnitSalePlan.setSalePlanMainId(tbMain.getId());
                tbUnitSalePlan.setSaleId(CommonUtils.createSaleID(tbMain.getPlaceUnitId(), startDate, tbMain.getStartTime(),tbMain.getEndTime()));       // getTbBizPlaceUnitSalePlan不是从数据库中读取的,此处拼接
                tbUnitSalePlan.setPlaceUnitName(tbMain.getPlaceUnitName());
                tbUnitSalePlan.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                tbUnitSalePlan.setStartTime(tbMain.getStartTime());
                tbUnitSalePlan.setEndTime(tbMain.getEndTime());
                tbUnitSalePlan.setPrice(tbMain.getPrice());
                tbUnitSalePlan.setMemberPrice(tbMain.getMemberPrice());
                tbUnitSalePlan.setIsEffective(Constants.IS_ENABLE_TRUE);
                if (tbMain.getBundleNo() != null){
                    if (tbMain.getBundleNo() == 0){
                        tbUnitSalePlan.setBundleNo(0);
                    } else {
                        String bundleNo = tbMain.getPlaceUnitId()+""+tbMain.getBundleNo();
                        tbUnitSalePlan.setBundleNo(Integer.valueOf(bundleNo));
                    }
                }

                tbUnitSalePlan.setUnitType(tbMain.getUnitType());  // 从模板中获取场地类型

                if (PlaceConstants.UNIT_TYPE_COMBINE.equals(tbMain.getUnitType())) {
                    continue; // 商家端暂时不要处理组合场地的情况
                }

                resultList.add(tbUnitSalePlan);
            }
            //开单插入销售计划
            this.addTbUnitSalePlanForBilling(resultList);
        }
        Map<String, TbBizPlaceUnitSalePlan> resultMap = new LinkedHashMap();
        //去除重复销售计划
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : resultList) {
            if (!resultMap.containsKey(tbBizPlaceUnitSalePlan.getSaleId())) {
                resultMap.put(tbBizPlaceUnitSalePlan.getSaleId(), tbBizPlaceUnitSalePlan);
            }
        }
        List<TbBizPlaceUnitSalePlan> districtList = new ArrayList<>();
        for (Map.Entry<String, TbBizPlaceUnitSalePlan> entry : resultMap.entrySet()) {
            districtList.add(entry.getValue());
        }
        RespPlaceUnitSalePlanDetail respPlaceUnitSalePlanDetail = null;
        if (!StringUtils.isEmpty(reqPlaceSalePlan.getFrom())) {
            respPlaceUnitSalePlanDetail = this.baseService.getSalePlanDetail(reqPlaceSalePlan, reqPlaceSalePlan.getFrom(), districtList);
        }
        if (StringUtils.isEmpty(respPlaceUnitSalePlanDetail)) {
            logger.warn("==================没有可用的销售计划");
            return APIResponse.returnFail("没有销售计划");
        }
        logger.warn("==================可用的销售计划:{}", JSON.toJSON(respPlaceUnitSalePlanDetail));
        return APIResponse.returnSuccess(respPlaceUnitSalePlanDetail);
    }

    /**
     * 包场添加销售计划（扫码支付）
     *
     * @param tbBizPlaceUnitSalePlans
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private boolean addTbUnitSalePlanForScanPay(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans) throws Exception {

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return false;
        }
        for (TbBizPlaceUnitSalePlan tbSalePlan : tbBizPlaceUnitSalePlans) {
            TbBizPlaceUnitSalePlanExample tbSalePlanExample = new TbBizPlaceUnitSalePlanExample();
            TbBizPlaceUnitSalePlanExample.Criteria criteria = tbSalePlanExample.createCriteria();
            criteria.andPlaceIdEqualTo(tbSalePlan.getPlaceId()).andCategoryIdEqualTo(tbSalePlan.getCategoryId())
                    .andIsEffectiveEqualTo(Constants.IS_ENABLE_TRUE).andPlaceUnitIdEqualTo(tbSalePlan.getPlaceUnitId())
                    .andDateEqualTo(tbSalePlan.getDate()).andTimeTypeEqualTo(tbSalePlan.getTimeType())
                    .andStartTimeEqualTo(tbSalePlan.getStartTime());
            tbSalePlanExample.setOrderByClause(" id for update ");
            List<TbBizPlaceUnitSalePlan> tbSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(tbSalePlanExample);
            if (CollectionUtils.isNotEmpty(tbSalePlans)) {
                for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbSalePlans){
                    if (tbBizPlaceUnitSalePlan.getStatus() != PlaceConstants.PLACE_PREORDER_STATUS){
                        throw new Exception("您所选场地部分已经出售或者被锁场！建议确认场地锁场信息");
                    }
                }
                tbSalePlan.setStatus(PlaceConstants.PLACE_LOCk_STATUS);
                tbSalePlan.setSaleId(tbSalePlan.getSaleId());
                tbBizPlaceUnitSalePlanMapper.updateByExampleSelective(tbSalePlan, tbSalePlanExample);
            } else {
                tbSalePlan.setStatus(PlaceConstants.PLACE_LOCk_STATUS);
                tbSalePlan.setSaleId(tbSalePlan.getSaleId());
                try{
                    this.tbBizPlaceUnitSalePlanMapper.insertSelective(tbSalePlan);
                }catch (Exception e){
                    logger.warn("包场重复添加销售计划"+e.getMessage());
                    throw new Exception("尝试插入包场销售计划失败，回滚事务");
                }
            }
        }
        return true;
    }

    /**
     * 包场添加销售计划
     *
     * @param tbBizPlaceUnitSalePlans
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private boolean addTbUnitSalePlan(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans) throws Exception {

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return false;
        }
        for (TbBizPlaceUnitSalePlan tbSalePlan : tbBizPlaceUnitSalePlans) {
            TbBizPlaceUnitSalePlanExample tbSalePlanExample = new TbBizPlaceUnitSalePlanExample();
            TbBizPlaceUnitSalePlanExample.Criteria criteria = tbSalePlanExample.createCriteria();
            criteria.andPlaceIdEqualTo(tbSalePlan.getPlaceId()).andCategoryIdEqualTo(tbSalePlan.getCategoryId())
                    .andIsEffectiveEqualTo(Constants.IS_ENABLE_TRUE).andPlaceUnitIdEqualTo(tbSalePlan.getPlaceUnitId())
                    .andDateEqualTo(tbSalePlan.getDate()).andTimeTypeEqualTo(tbSalePlan.getTimeType())
                    .andStartTimeEqualTo(tbSalePlan.getStartTime())
                    .andEndTimeEqualTo(tbSalePlan.getEndTime());
            tbSalePlanExample.setOrderByClause(" id for update ");
            List<TbBizPlaceUnitSalePlan> tbSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(tbSalePlanExample);
            if (CollectionUtils.isNotEmpty(tbSalePlans)) {
                for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbSalePlans){
                    if (tbBizPlaceUnitSalePlan.getStatus().intValue() != PlaceConstants.PLACE_PREORDER_STATUS.intValue()){
                        throw new Exception("您所选场地部分已经出售或者被锁场！建议确认场地锁场信息");
                    }
                }
                tbSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
                tbSalePlan.setSaleId(tbSalePlan.getSaleId());
                tbBizPlaceUnitSalePlanMapper.updateByExampleSelective(tbSalePlan, tbSalePlanExample);
            } else {

                tbSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
                tbSalePlan.setSaleId(tbSalePlan.getSaleId());

                try{
                    this.tbBizPlaceUnitSalePlanMapper.insertSelective(tbSalePlan);
                }catch (Exception e){
                    logger.warn("包场重复添加销售计划"+e.getMessage());
                    throw new Exception("尝试插入包场销售计划失败，回滚事务");
                }

                logger.debug("====================================增加销售计划 TbBizPlaceUnitSalePlan:{}",
                        JSON.toJSONString(tbSalePlan));
            }
        }
        return true;
    }

    /**
     * 开单添加销售计划
     *
     * @param tbBizPlaceUnitSalePlans
     * @return
     */
    private boolean addTbUnitSalePlanForBilling(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans) {

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return false;
        }
        for (TbBizPlaceUnitSalePlan tbSalePlan : tbBizPlaceUnitSalePlans) {
            TbBizPlaceUnitSalePlanExample tbSalePlanExample = new TbBizPlaceUnitSalePlanExample();
            TbBizPlaceUnitSalePlanExample.Criteria criteria = tbSalePlanExample.createCriteria();
            criteria.andPlaceIdEqualTo(tbSalePlan.getPlaceId()).andCategoryIdEqualTo(tbSalePlan.getCategoryId())
                    /*.andIsEffectiveEqualTo(Constants.IS_ENABLE_TRUE)*/.andPlaceUnitIdEqualTo(tbSalePlan.getPlaceUnitId())
                    .andDateEqualTo(tbSalePlan.getDate()).andTimeTypeEqualTo(tbSalePlan.getTimeType())
                    .andStartTimeEqualTo(tbSalePlan.getStartTime()).andEndTimeEqualTo(tbSalePlan.getEndTime());
            List<TbBizPlaceUnitSalePlan> tbSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(tbSalePlanExample);
            if (CollectionUtils.isNotEmpty(tbSalePlans)) {

                /*tbSalePlan.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                tbSalePlan.setSaleId(tbSalePlan.getSaleId());
                tbBizPlaceUnitSalePlanMapper.updateByExampleSelective(tbSalePlan, tbSalePlanExample);*/
            } else {

                tbSalePlan.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                tbSalePlan.setSaleId(tbSalePlan.getSaleId());
                this.tbBizPlaceUnitSalePlanMapper.insertSelective(tbSalePlan);
            }
        }
        return true;
    }

    @Transactional
    public APIResponse<?> createBook(ReqBillingInfo reqBillingInfo, List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans)
            throws Exception {

        List<String> weekList = new ArrayList();
        List<Integer> weeks = reqBillingInfo.getWeek();
        for (Integer list1 : weeks) {
            String para = list1.toString();
            weekList.add(para);
        }

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return APIResponse.returnFail("销售计划为空");
        }

        String orderid = baseService.getBizOrderId(reqBillingInfo.getCreateUid());
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = baseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
                reqBillingInfo.getCreateUid(), orderid, PlaceConstants.PRIVATE_USE_TYPE,reqBillingInfo,PlaceConstants.PRIVATE_USE_TYPE);//1 为包场会员价
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
            return APIResponse.returnFail("订单明细为空");
        }
        BigDecimal price = new BigDecimal(0);
        List<TbBizPlaceOrderItem> notMemberTbBizPlaceOrderItems = baseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
                reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.PRIVATE_USE_TYPE);//0 为普通价
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
            //插入明细
            price = price.add(item.getSalePrice());
        }
        BigDecimal notMemberPrice = new BigDecimal(0);
        for (TbBizPlaceOrderItem item : notMemberTbBizPlaceOrderItems) {
            //订单价格
            notMemberPrice = notMemberPrice.add(item.getSalePrice());
        }
        //插入父订单
        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = new TbBizPlacePrivateOrder();
        tbBizPlacePrivateOrder.setPlaceOrderId(orderid);
        tbBizPlacePrivateOrder.setCategoryId(reqBillingInfo.getCategoryId());
        tbBizPlacePrivateOrder.setCustomerName(StringUtils.isEmpty(reqBillingInfo.getName()) ? "散客":reqBillingInfo.getName());
        tbBizPlacePrivateOrder.setMobile(reqBillingInfo.getContactInformation());
        tbBizPlacePrivateOrder.setDescrible(reqBillingInfo.getMemo());
        tbBizPlacePrivateOrder.setPlaceId(reqBillingInfo.getPlaceId());
        tbBizPlacePrivateOrder.setCreateUid(reqBillingInfo.getCreateUid());
        tbBizPlacePrivateOrder.setPaymentTime(new Date());
        tbBizPlacePrivateOrder.setDebit(notMemberPrice);
        tbBizPlacePrivateOrder.setDate(new Date());
        tbBizPlacePrivateOrder.setEndTime(new Date());
        tbBizPlacePrivateOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
        tbBizPlacePrivateOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        tbBizPlacePrivateOrder.setOrderStatusChangeDate(new Date());
        tbBizPlacePrivateOrder.setParentId(0);
        tbBizPlacePrivateOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
        tbBizPlacePrivateOrder.setStartDate(DateUtils.transferLongToDate(reqBillingInfo.getStartDate()));
        tbBizPlacePrivateOrder.setEndDate(DateUtils.transferLongToDate(reqBillingInfo.getEndDate()));
        tbBizPlacePrivateOrder.setWeeks(JSON.toJSONString(weeks));
        tbBizPlacePrivateOrder.setHandAdjustAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()).subtract(notMemberPrice));
        tbBizPlacePrivateOrder.setUseType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
        if (!StringUtils.isEmpty(reqBillingInfo.getExpression())){
            tbBizPlacePrivateOrder.setExpression(reqBillingInfo.getExpression());
        }else{
            tbBizPlacePrivateOrder.setExpression("");
        }

        //普通支付
        tbBizPlacePrivateOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
        tbBizPlacePrivateOrder.setPayStatus(PlaceConstants.PAY_STATUS);

        Integer porderid = 0;
        if (this.tbBizPlacePrivateOrderMapper.insertSelective(tbBizPlacePrivateOrder) != 0) {
            porderid = tbBizPlacePrivateOrder.getId();
            logger.debug("========================插入订单数据:tbBizPlacePrivateOrder:{}", JSON.toJSONString(tbBizPlacePrivateOrder));
        }
        //按日期插入订单明细数据
        Date startDate = new Date(reqBillingInfo.getStartDate());
        Date endDate = new Date(reqBillingInfo.getEndDate());
        Map map = addOrderDetail(tbBizPlaceUnitSalePlans, startDate, endDate, reqBillingInfo, porderid, weeks, 100, null,tbBizPlacePrivateOrder);
        if (MapUtils.isEmpty(map)) {
            throw new Exception("生成子订单异常");
        }
        List<TbBizPlaceOrder> orders = new ArrayList<>();
        List<TbBizPlaceOrderItem> items = new ArrayList<>();
        List<TbBizPlacePayItem> pays = new ArrayList<>();
        orders = (List<TbBizPlaceOrder>) MapUtils.getObject(map, "orders");
        items = (List<TbBizPlaceOrderItem>) MapUtils.getObject(map, "items");
        pays = (List<TbBizPlacePayItem>) MapUtils.getObject(map, "pays");

        //记录未调价的订单明细
        List<TbBizPlaceOrderItem> oldOrderItems = new ArrayList<>();
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : items ){
            TbBizPlaceOrderItem tbBizPlaceOrderItem1 = new TbBizPlaceOrderItem();
            BeanUtils.copyProperties(tbBizPlaceOrderItem,tbBizPlaceOrderItem1);
            oldOrderItems.add(tbBizPlaceOrderItem1);
        }

        //调整金额  计算
        this.calcAmount(orders,items,pays,reqBillingInfo,tbBizPlacePrivateOrder);


        //修改支付明细--现在改为按  订单明细-->支付明细
        List<TbBizPlacePayItem> placePayItemList = iBaseService.convertOrderPayItem(items, reqBillingInfo.getAdminPayType(), null);
        //生成订单折扣明细
        List<TbBizPlaceOrderDiscountItem> placeOrderDiscountItemList =  this.createBlockOrderDiscountItem(oldOrderItems, items, null);

        //add to db
        boolean flag = addOrders(orders, items, placePayItemList, placeOrderDiscountItemList, reqBillingInfo, null);
        if (!flag) {
            throw new Exception("保存失败");
        }

       Map orderItemsMap = this.getTbBizPlaceItemListByPlaceOrderId(items);
        //插入支付流水
        List<ReqOrderHistory> reqOrderHistoryList = new ArrayList<>();
        for (TbBizPlaceOrder tbBizPlaceOrder : orders){
            List<TbBizPlaceOrderItem> singleTbBizPlaceOrderItems = (List<TbBizPlaceOrderItem>)orderItemsMap.get(tbBizPlaceOrder.getPlaceOrderId());
            List<ReqOrderHistory> singleOrderHistory = placeOrderUtilService.tbBizPlaceOrderItem2ReqOrderHistory(tbBizPlaceOrder,singleTbBizPlaceOrderItems,(byte)0,(byte)0,null);
            reqOrderHistoryList.addAll(singleOrderHistory);
        }
        if (CollectionUtils.isNotEmpty(reqOrderHistoryList)){
            placeOrderUtilService.shoppingCartOrderInsertOrderHistory(reqOrderHistoryList);
        }
        return APIResponse.returnSuccess(tbBizPlacePrivateOrder);
    }

    /**
     * 包场生成优惠明细
     * @param oldItems
     * @param newItems
     * @param memberCard
     * @return
     */
    private List<TbBizPlaceOrderDiscountItem> createBlockOrderDiscountItem(List<TbBizPlaceOrderItem> oldItems,List<TbBizPlaceOrderItem> newItems,TbBizPlaceMemberCard memberCard){
        List<TbBizPlaceOrderDiscountItem>  result = new ArrayList<TbBizPlaceOrderDiscountItem>();
        if (CollectionUtils.isNotEmpty(newItems) && CollectionUtils.isNotEmpty(oldItems)){
            for (TbBizPlaceOrderItem newItem : newItems){
                for (TbBizPlaceOrderItem oldItem : oldItems){
                    if (newItem.getItemUuid().equals(oldItem.getItemUuid())){
                        TbBizPlaceOrderDiscountItem discountItem = new TbBizPlaceOrderDiscountItem();
                        discountItem.setOrderItemUuid(newItem.getItemUuid());
                        discountItem.setPlaceOrderId(newItem.getPlaceOrderId());
                        discountItem.setStatus(newItem.getStatus());
                        if (!StringUtils.isEmpty(memberCard)){
                            //包场会员和非会员都是取会员价
                            discountItem.setDiscountMember(newItem.getOriginPrice().subtract(newItem.getMemberPrice()));
                            BigDecimal memberDiscount = newItem.getMemberPrice().multiply(new BigDecimal(100-(StringUtils.isEmpty(memberCard.getDiscount())? 100:memberCard.getDiscount())).divide(new BigDecimal(100)));
                            discountItem.setDiscountDiscountMember(memberDiscount.compareTo(BigDecimal.ZERO)==0?null:memberDiscount);
                            discountItem.setMemberCardNo(memberCard.getInnerCardNo());
                        }
                        BigDecimal adjust = oldItem.getSalePrice().subtract(newItem.getSalePrice());
                        discountItem.setDiscountAdjust(adjust.compareTo(BigDecimal.ZERO)==0?null:adjust);

                        result.add(discountItem);
                    }
                }
            }
        }
        return result;
    }

    private Map<String, List<TbBizPlaceOrderItem>> getTbBizPlaceItemListByPlaceOrderId(List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList) {
        Map<String, List<TbBizPlaceOrderItem>> map = new HashMap();

        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList) {

            if (!map.containsKey(tbBizPlaceOrderItem.getPlaceOrderId())) {
                List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = new ArrayList<>();
                map.put(tbBizPlaceOrderItem.getPlaceOrderId(), tbBizPlaceOrderItems);
            }
            List<TbBizPlaceOrderItem> tbBizPlaceUnitSalePlanTemp = map
                    .get(tbBizPlaceOrderItem.getPlaceOrderId());
            tbBizPlaceUnitSalePlanTemp.add(tbBizPlaceOrderItem);

        }
        return map;
    }

    @Transactional
    public TbBizPlacePrivateOrder createBookForScanPay(ReqBillingInfo reqBillingInfo, List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans)
            throws Exception {

        List<String> weekList = new ArrayList();
        List<Integer> weeks = reqBillingInfo.getWeek();
        for (Integer list1 : weeks) {
            String para = list1.toString();
            weekList.add(para);
        }

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            throw new Exception("销售计划为空");
        }

        String orderid = baseService.getBizOrderId(reqBillingInfo.getCreateUid());
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = baseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
                reqBillingInfo.getCreateUid(), orderid, PlaceConstants.PRIVATE_USE_TYPE,reqBillingInfo,PlaceConstants.PRIVATE_USE_TYPE);//1 为包场会员价
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
            throw new Exception("订单明细为空");
        }
        BigDecimal price = new BigDecimal(0);
        List<TbBizPlaceOrderItem> notMemberTbBizPlaceOrderItems = baseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
                reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.PRIVATE_USE_TYPE);//0 为普通价
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
            //插入明细
            price = price.add(item.getSalePrice());
        }
        BigDecimal notMemberPrice = new BigDecimal(0);
        for (TbBizPlaceOrderItem item : notMemberTbBizPlaceOrderItems) {
            //订单价格
            notMemberPrice = notMemberPrice.add(item.getSalePrice());
        }
        //插入父订单
        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = new TbBizPlacePrivateOrder();
        tbBizPlacePrivateOrder.setPlaceOrderId(orderid);
        tbBizPlacePrivateOrder.setCategoryId(reqBillingInfo.getCategoryId());
        tbBizPlacePrivateOrder.setCustomerName(StringUtils.isEmpty(reqBillingInfo.getName()) ? "散客":reqBillingInfo.getName());
        tbBizPlacePrivateOrder.setMobile(reqBillingInfo.getContactInformation());
        tbBizPlacePrivateOrder.setDescrible(reqBillingInfo.getMemo());
        tbBizPlacePrivateOrder.setPlaceId(reqBillingInfo.getPlaceId());
        tbBizPlacePrivateOrder.setCreateUid(reqBillingInfo.getCreateUid());
        tbBizPlacePrivateOrder.setPaymentTime(null);
        tbBizPlacePrivateOrder.setDebit(notMemberPrice);
        tbBizPlacePrivateOrder.setUid(reqBillingInfo.getCreateUid());//增加用户uid
        tbBizPlacePrivateOrder.setDate(new Date());
        tbBizPlacePrivateOrder.setEndTime(new Date());
        tbBizPlacePrivateOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
        tbBizPlacePrivateOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        tbBizPlacePrivateOrder.setOrderStatusChangeDate(new Date());
        tbBizPlacePrivateOrder.setParentId(0);
        tbBizPlacePrivateOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
        tbBizPlacePrivateOrder.setStartDate(DateUtils.transferLongToDate(reqBillingInfo.getStartDate()));
        tbBizPlacePrivateOrder.setEndDate(DateUtils.transferLongToDate(reqBillingInfo.getEndDate()));
        tbBizPlacePrivateOrder.setWeeks(JSON.toJSONString(weeks));
        tbBizPlacePrivateOrder.setHandAdjustAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()).subtract(price));
        tbBizPlacePrivateOrder.setUseType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
        if (!StringUtils.isEmpty(reqBillingInfo.getExpression())){
            tbBizPlacePrivateOrder.setExpression(reqBillingInfo.getExpression());
        }else{
            tbBizPlacePrivateOrder.setExpression("");
        }

        //扫码支付
        tbBizPlacePrivateOrder.setOrderStatus(PlaceConstants.NOT_PAY_STATUS);
        tbBizPlacePrivateOrder.setPayStatus(PlaceConstants.ORDER_PREPAY_STATUS);

        Integer porderid = 0;
        if (this.tbBizPlacePrivateOrderMapper.insertSelective(tbBizPlacePrivateOrder) != 0) {
            porderid = tbBizPlacePrivateOrder.getId();
            logger.debug("========================插入订单数据:tbBizPlacePrivateOrder:{}", JSON.toJSONString(tbBizPlacePrivateOrder));
        }
        //按日期插入订单明细数据
        Date startDate = new Date(reqBillingInfo.getStartDate());
        Date endDate = new Date(reqBillingInfo.getEndDate());
        Map map = addOrderDetail(tbBizPlaceUnitSalePlans, startDate, endDate, reqBillingInfo, porderid, weeks, 100, null,tbBizPlacePrivateOrder);
        if (MapUtils.isEmpty(map)) {
            throw new Exception("生成子订单异常");
        }
        List<TbBizPlaceOrder> orders = new ArrayList<>();
        List<TbBizPlaceOrderItem> items = new ArrayList<>();
        List<TbBizPlacePayItem> pays = new ArrayList<>();
        orders = (List<TbBizPlaceOrder>) MapUtils.getObject(map, "orders");
        items = (List<TbBizPlaceOrderItem>) MapUtils.getObject(map, "items");
        pays = (List<TbBizPlacePayItem>) MapUtils.getObject(map, "pays");

        //修改子订单状态与父订单状态一致
        for (TbBizPlaceOrder tbBizPlaceOrder : orders){
            tbBizPlaceOrder.setOrderStatus(tbBizPlacePrivateOrder.getOrderStatus());
            tbBizPlaceOrder.setPayStatus(tbBizPlacePrivateOrder.getPayStatus());
        }

        //调整金额  计算
        this.calcAmount(orders,items,pays,reqBillingInfo,tbBizPlacePrivateOrder);
        if(reqBillingInfo.getAdminPayType().toString().equals(PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY)){// pos支付成功生成支付明细
        	pays.clear();
        }
        //add to db
        boolean flag = addOrders(orders, items, pays, null, reqBillingInfo, null);
        if (!flag) {
            throw new Exception("保存失败");
        }

        return tbBizPlacePrivateOrder;
    }


    /**
     * 调整金额  计算
     * @param orders
     * @param items
     * @param pays
     * @param reqBillingInfo
     * @param tbBizPlacePrivateOrder
     */
    private void calcAmount(List<TbBizPlaceOrder> orders,
                            List<TbBizPlaceOrderItem> items,
                            List<TbBizPlacePayItem> pays,
                            ReqBillingInfo reqBillingInfo,
                            TbBizPlacePrivateOrder tbBizPlacePrivateOrder){
        //包场所有子订单订单应实付金额
        BigDecimal totalOrderPrice = new BigDecimal(0);

        //单个订单实付金额
        BigDecimal singleOrderPayPrice = new BigDecimal(0);
        //单个订单明细实付金额
        BigDecimal singleOrderItemPrice = new BigDecimal(0);
        //下标
        int indexOrder = 0;
        int indexItem = 0;
        int indexPay = 0;
        //最后一个之前的所有手动调整金额
        BigDecimal beforeHandAdjustAmount = new BigDecimal(0);

        //最后一个之前的所有明细金额
        BigDecimal beforeOrderItemAmount = new BigDecimal(0);

        //最后一个之前的所有明细金额
        BigDecimal beforeOrderPayAmount = new BigDecimal(0);

        for (TbBizPlacePayItem tbBizPlacePayItem : pays){
            singleOrderPayPrice = new BigDecimal(reqBillingInfo.getReceivedAmount()).divide(new BigDecimal(pays.size()),2,BigDecimal.ROUND_HALF_UP);
            indexPay ++;
            if (indexPay != pays.size()){
                beforeOrderPayAmount = beforeOrderPayAmount.add(singleOrderPayPrice);
            }
            if (indexPay == pays.size()){
                singleOrderPayPrice = new BigDecimal(reqBillingInfo.getReceivedAmount()).subtract(beforeOrderPayAmount);
            }
            tbBizPlacePayItem.setAmount(singleOrderPayPrice);
            totalOrderPrice = totalOrderPrice.add(singleOrderPayPrice);
        }



        BigDecimal totalSalePrice = new BigDecimal(0);
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : items) {
            totalSalePrice = totalSalePrice.add(tbBizPlaceOrderItem.getSalePrice()); 
        }
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : items){
            singleOrderItemPrice = tbBizPlaceOrderItem.getSalePrice().multiply(new BigDecimal(reqBillingInfo.getReceivedAmount())).divide(totalSalePrice,2,BigDecimal.ROUND_HALF_UP);
            tbBizPlaceOrderItem.setSalePrice(singleOrderItemPrice);
            indexItem ++;
            if (indexItem != items.size()) {
                beforeOrderItemAmount = beforeOrderItemAmount.add(singleOrderItemPrice);
            }
            if (indexItem == items.size()){
                tbBizPlaceOrderItem.setSalePrice(new BigDecimal(reqBillingInfo.getReceivedAmount()).subtract(beforeOrderItemAmount));
            }
        }

        //解决 订单明细跟付款明细不一致情况
        for (TbBizPlacePayItem tbBizPlacePayItem : pays){
        	
            BigDecimal tempPayPrice = new BigDecimal(0);
            
            for (TbBizPlaceOrderItem tbBizPlaceOrderItem : items){
                if (tbBizPlacePayItem.getPlaceOrderId().equals(tbBizPlaceOrderItem.getPlaceOrderId())){
                    tempPayPrice = tempPayPrice.add(tbBizPlaceOrderItem.getSalePrice());
                }
            }
            
            tbBizPlacePayItem.setAmount(tempPayPrice);
        }

        for (TbBizPlaceOrder order : orders) {
            order.setEnableRefund(reqBillingInfo.getEnableRefund().byteValue());
            for (TbBizPlacePayItem tbBizPlacePayItem : pays){
                //单个订单应实付金额
                BigDecimal singleOrderPrice = new BigDecimal(0);
                if (order.getPlaceOrderId().equals(tbBizPlacePayItem.getPlaceOrderId())){
                    singleOrderPrice = singleOrderPrice.add(tbBizPlacePayItem.getAmount());
                    // (子订单实收金额 * 优惠价) / 父订单实收金额
                    BigDecimal singleAdjustAmount = (singleOrderPrice.multiply(tbBizPlacePrivateOrder.getHandAdjustAmount()))
                            .divide(totalOrderPrice,2,BigDecimal.ROUND_HALF_UP);
                    order.setHandAdjustAmount(singleAdjustAmount);
                    indexOrder ++ ;
                    if (indexOrder != orders.size()){
                        beforeHandAdjustAmount = beforeHandAdjustAmount.add(singleAdjustAmount);
                    }
                    if (indexOrder == orders.size()){
                        order.setHandAdjustAmount(tbBizPlacePrivateOrder.getHandAdjustAmount().subtract(beforeHandAdjustAmount.setScale(2, BigDecimal.ROUND_HALF_UP)));
                    }
                }
            }
        }
    }

    @Transactional
    private boolean addOrders(final List<TbBizPlaceOrder> orders, final List<TbBizPlaceOrderItem> items,
                              final List<TbBizPlacePayItem> pays, final List<TbBizPlaceOrderDiscountItem> disounts,
                              final ReqBillingInfo reqBillingInfo,
                              final Integer memberUid) {
        if (CollectionUtils.isEmpty(orders) && CollectionUtils.isEmpty(items) && CollectionUtils.isEmpty(pays)) {
            return false;
        }
        
        try {
        	  if( CollectionUtils.isNotEmpty(orders) ) {
//                String ordersql = "INSERT INTO `tb_biz_place_order` (`place_order_id`, `place_id`, `category_id`, " +
//                "`date`, `debit`, `order_time`, `payment_time`, `end_time`, " +
//                "`order_status_change_date`, `pay_status`, `order_status`, `uid`, `customer_name`," +
//                " `mobile`, `source_type`, `use_type`, `is_effective`, `describle`, `parent_id`, `enable_refund`," +
//                " `create_uid`, `update_uid`, `create_time`, `update_time`, `platform`)" +
//                "VALUES" +
//                "( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?);";
		        String ordersql = "INSERT INTO `tb_biz_place_order` (`place_order_id`, `place_id`, `category_id`, " +
		                "`date`, `debit`, `order_time`, `payment_time`, `end_time`, " +
		                "`order_status_change_date`, `pay_status`, `order_status`, `uid`, `customer_name`," +
		                " `mobile`, `source_type`, `use_type`, `is_effective`, `describle`, `parent_id`,`business_mode`, `enable_refund`," +
		                " `create_uid`, `update_uid`,  `platform`, `hand_adjust_amount`,`expression`,`order_channel`,`is_member`,`inner_card_no`,`is_type`)" +
		                "VALUES" +
		                "( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?);";
		
		        jdbcTemplate.batchUpdate(ordersql, new BatchPreparedStatementSetter() {
		            public void setValues(PreparedStatement ps, int i) throws SQLException {
		                TbBizPlaceOrder tbBizPlaceOrder = orders.get(i);
		                int k = 1;
		                ps.setString(k++, tbBizPlaceOrder.getPlaceOrderId());
		                ps.setInt(k++, tbBizPlaceOrder.getPlaceId());
		                ps.setInt(k++, tbBizPlaceOrder.getCategoryId());
		                ps.setDate(k++, new java.sql.Date(tbBizPlaceOrder.getDate().getTime()));
		                ps.setBigDecimal(k++, tbBizPlaceOrder.getDebit());
		//                ps.setTimestamp(k++, new Timestamp(tbBizPlaceOrder.getOrderTime().getTime()) );
		//                ps.setTimestamp(k++, new Timestamp(tbBizPlaceOrder.getPaymentTime().getTime()));
		//                ps.setTimestamp(k++, new Timestamp(tbBizPlaceOrder.getEndTime().getTime()));
		//                ps.setTimestamp(k++, new Timestamp( tbBizPlaceOrder.getOrderStatusChangeDate().getTime()));
		                ps.setTimestamp(k++, new Timestamp(new Date().getTime()));
		                ps.setTimestamp(k++, tbBizPlaceOrder.getPaymentTime() != null? new Timestamp(tbBizPlaceOrder.getPaymentTime().getTime()) : null);
		                ps.setTimestamp(k++, tbBizPlaceOrder.getEndTime() != null? new Timestamp(tbBizPlaceOrder.getEndTime().getTime()) : null);
		                ps.setTimestamp(k++, null);
		                ps.setInt(k++, tbBizPlaceOrder.getPayStatus());
		                ps.setInt(k++, tbBizPlaceOrder.getOrderStatus());
		                if (StringUtils.isEmpty(memberUid)) {
		                    ps.setInt(k++, reqBillingInfo.getCreateUid());
		                } else {
		                    ps.setInt(k++, memberUid);
		                }
		                ps.setString(k++, tbBizPlaceOrder.getCustomerName());
		                ps.setString(k++, reqBillingInfo.getContactInformation());
		                ps.setInt(k++, PlaceConstants.SOURCE_TYPE_SCENEPAY);
		                ps.setInt(k++, 1);
		                ps.setInt(k++, tbBizPlaceOrder.getIsEffective());
		                ps.setString(k++, reqBillingInfo.getMemo());
		                ps.setInt(k++, tbBizPlaceOrder.getParentId());
		                ps.setInt(k++,tbBizPlaceOrder.getBusinessMode());
		                ps.setInt(k++, tbBizPlaceOrder.getEnableRefund().byteValue());
		                ps.setInt(k++, reqBillingInfo.getCreateUid());
		                ps.setInt(k++, reqBillingInfo.getCreateUid());
		//                ps.setTimestamp(k++, new Timestamp( tbBizPlaceOrder.getCreateTime().getTime()));
		//                ps.setTimestamp(k++, new Timestamp(tbBizPlaceOrder.getUpdateTime().getTime()));
		//                ps.setTimestamp(k++, new Timestamp( new Date().getTime()));
		//                ps.setTimestamp(k++, new Timestamp( new Date().getTime()));
		                ps.setInt(k++, PlatformTypeEnum.BACKSTAGE.getId());
		                ps.setBigDecimal(k++,tbBizPlaceOrder.getHandAdjustAmount());
		                ps.setString(k++,tbBizPlaceOrder.getExpression());
		                ps.setInt(k++,tbBizPlaceOrder.getOrderChannel());
		                ps.setInt(k++,tbBizPlaceOrder.getIsMember());
		                ps.setString(k++,tbBizPlaceOrder.getInnerCardNo());
                        ps.setObject(k++,tbBizPlaceOrder.getIsType());
		            }
		
		            public int getBatchSize() {
		                return orders.size();
		            }
		        });
              }
        	  
        	  if( CollectionUtils.isNotEmpty(items) ) {
//                String itemsql = "INSERT INTO `tb_biz_place_order_item` (`place_order_id`, `unit_sale_plan_id`, `sale_id`, " +
//                "`version`, `sale_price`, `create_uid`, `update_uid`, `create_time`, `update_time`)" +
//                "VALUES" +
//                "(?,?,?,?,?,?,?,?,?);";
		        String itemsql = "INSERT INTO `tb_biz_place_order_item` (`place_order_id`, `unit_sale_plan_id`, `sale_id`, " +
		                "`version`, `sale_price`, `create_uid`, `update_uid`, `consume_time`, `item_uuid`,`use_type`,`goods_id`," +
		                "`goods_name`,`surplus_goods_count`,`total_goods_count`,`start_time`,`end_time`,`origin_price`,`member_price`,`category_id`,`ticket_count`)" +
		                "VALUES" +
		                "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
		
		        jdbcTemplate.batchUpdate(itemsql, new BatchPreparedStatementSetter() {
		            @Override
		            public void setValues(PreparedStatement ps, int i) throws SQLException {
		                TbBizPlaceOrderItem tbBizPlaceOrderItem = items.get(i);
		                ps.setString(1, tbBizPlaceOrderItem.getPlaceOrderId());
		                ps.setObject(2, tbBizPlaceOrderItem.getUnitSalePlanId());//销售计划id  拿不到
		                ps.setString(3, tbBizPlaceOrderItem.getSaleId());
		                ps.setInt(4, tbBizPlaceOrderItem.getVersion());
		                ps.setBigDecimal(5, tbBizPlaceOrderItem.getSalePrice());
		                ps.setInt(6, reqBillingInfo.getCreateUid());
		                ps.setInt(7, reqBillingInfo.getCreateUid());
		                ps.setObject(8,tbBizPlaceOrderItem.getConsumeTime());
		                ps.setString(9,tbBizPlaceOrderItem.getItemUuid());
		                ps.setInt(10,tbBizPlaceOrderItem.getUseType());
		                ps.setObject(11,tbBizPlaceOrderItem.getGoodsId());
		                ps.setString(12,tbBizPlaceOrderItem.getGoodsName());
		                ps.setInt(13,tbBizPlaceOrderItem.getSurplusGoodsCount());
		                ps.setInt(14,tbBizPlaceOrderItem.getTotalGoodsCount());
		                ps.setObject(15,tbBizPlaceOrderItem.getStartTime());
		                ps.setObject(16,tbBizPlaceOrderItem.getEndTime());
		                ps.setObject(17,tbBizPlaceOrderItem.getOriginPrice());
		                ps.setObject(18,tbBizPlaceOrderItem.getMemberPrice());
		                ps.setObject(19, tbBizPlaceOrderItem.getCategoryId());
                        ps.setObject(20, tbBizPlaceOrderItem.getTicketCount());
		            }
		
		            @Override
		            public int getBatchSize() {
		                return items.size();
		            }
		        });

        	  }

        	if( CollectionUtils.isNotEmpty(pays) ) {
        		 String payItemsql = "INSERT INTO `tb_biz_place_pay_item` ( `place_order_id`, `pay_type`, `amount`," +
                         " `amount_type`, `admin_pay_type`,`order_item_uuid`)" +
                         "VALUES" +
                         "(?,?,?,?,? ,?);";
                 jdbcTemplate.batchUpdate(payItemsql, new BatchPreparedStatementSetter() {
                     @Override
                     public void setValues(PreparedStatement ps, int i) throws SQLException {
                    	 TbBizPlacePayItem pay = pays.get(i);
                         ps.setString(1, pay.getPlaceOrderId());
                         ps.setInt(2, pay.getPayType());
                         ps.setBigDecimal(3, pay.getAmount());
                         ps.setInt(4, PlaceConstants.DEBIT_TYPE);
                         ps.setInt(5, pay.getAdminPayType());
                         ps.setString(6,pay.getOrderItemUuid());
                     }

                     @Override
                     public int getBatchSize() {
                         return pays.size();
                     }
                 });
        	}

        	//批量写入优惠明细
        	if (CollectionUtils.isNotEmpty(disounts)) {
        		String paysql = " insert into tb_biz_place_order_discount_item (order_item_uuid, place_order_id, status, "+
                                " discount_egg, discount_coupon, discount_discount_coupon, discount_member, discount_discount_member, "+
                                " discount_adjust, member_card_no, egg_count, subject_amount, subject_discount, subject_code,  create_time, update_time)" +
                                " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
                jdbcTemplate.batchUpdate(paysql, new BatchPreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                        TbBizPlaceOrderDiscountItem discountItem = disounts.get(i);
                        ps.setString(1, discountItem.getOrderItemUuid());
                        ps.setString(2, discountItem.getPlaceOrderId());
                        ps.setInt(3, discountItem.getStatus());
                        ps.setBigDecimal(4, discountItem.getDiscountEgg());
                        ps.setBigDecimal(5, discountItem.getDiscountCoupon());
                        ps.setBigDecimal(6, discountItem.getDiscountDiscountCoupon());
                        ps.setBigDecimal(7, discountItem.getDiscountMember());
                        ps.setBigDecimal(8, discountItem.getDiscountDiscountMember());
                        ps.setBigDecimal(9, discountItem.getDiscountAdjust());
                        ps.setString(10, discountItem.getMemberCardNo());
                        ps.setInt(11, discountItem.getEggCount() != null? discountItem.getEggCount():0);
                        ps.setBigDecimal(12,discountItem.getSubjectAmount());
                        ps.setInt(13, discountItem.getSubjectDiscount() != null? discountItem.getSubjectDiscount():0);
                        ps.setString(14, discountItem.getSubjectCode());
                        ps.setObject(15,discountItem.getCreateTime());
                        ps.setObject(16,discountItem.getUpdateTime());
                    }

                    @Override
                    public int getBatchSize() {
                        return disounts.size();
                    }
                });
			}


        } catch (Exception e) {
        	logger.error(e.getMessage());
            return false;
        }
        return true;
    }

    @Async
    public Map addOrderDetail(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans,
                              Date startDate, Date endDate, ReqBillingInfo reqBillingInfo, Integer pid,
                              List<Integer> weeks, double discount, TbBizPlaceMemberCard tbBizPlaceMemberCard,TbBizPlacePrivateOrder tbBizPlacePrivateOrder) {
        List<TbBizPlaceOrder> orders = new ArrayList<>();
        List<TbBizPlaceOrderItem> items = new ArrayList<>();
        List<TbBizPlacePayItem> pays = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlans)) {
            //循环日期
            Calendar ca = Calendar.getInstance();
            Date curDate = startDate;
            Map<String, List<TbBizPlaceUnitSalePlan>> tbBizPlaceUnitSalePlansMap =
                    getTbBizPlaceUnitSalePlanListByDay(tbBizPlaceUnitSalePlans);

            while (curDate.compareTo(endDate) <= 0) {
                ca.setTime(curDate);
                Integer week = Integer.parseInt(DateUtils.dayForWeeks(DateUtils.transferDateToString(curDate)));
                if (weeks.contains(week)) {
                    List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanTemp = tbBizPlaceUnitSalePlansMap
                            .get(DateUtils.transferDateToString(curDate));
                    //按日期生成订单对象
                    Map map = getTbBizPlaceOrderByDay(curDate, tbBizPlaceUnitSalePlanTemp, reqBillingInfo.getCreateUid(),
                            reqBillingInfo, pid, discount,tbBizPlaceMemberCard,tbBizPlacePrivateOrder);
                    if (MapUtils.isEmpty(map)) {
                        ca.add(Calendar.DATE, 1);
                        curDate = ca.getTime();
                        continue;
                    }
                    orders.add((TbBizPlaceOrder) MapUtils.getObject(map, "order"));
                    items.addAll((List<TbBizPlaceOrderItem>) MapUtils.getObject(map, "items"));
                    pays.add((TbBizPlacePayItem) MapUtils.getObject(map, "pays"));
                }
                ca.add(Calendar.DATE, 1);
                curDate = ca.getTime();
            }

            Map map1 = new HashMap();
            map1.put("orders", orders);
            map1.put("items", items);
            map1.put("pays", pays);
            return map1;
        }
        return null;
    }

    private Map<String, List<TbBizPlaceUnitSalePlan>> getTbBizPlaceUnitSalePlanListByDay(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList) {
        Map<String, List<TbBizPlaceUnitSalePlan>> map = new HashMap();

        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {

            if (!map.containsKey((DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate())))) {
                List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = new ArrayList<>();
                map.put(DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate()), tbBizPlaceUnitSalePlans);
            }
            List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanTemp = map
                    .get(DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate()));
            tbBizPlaceUnitSalePlanTemp.add(tbBizPlaceUnitSalePlan);

        }
        return map;
    }

    private Map getTbBizPlaceOrderByDay(final Date date,
                                        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans,
                                        Integer uid,
                                        ReqBillingInfo reqBillingInfo,
                                        Integer porderid,
                                        double discount,
                                        TbBizPlaceMemberCard tbBizPlaceMemberCard,
                                        TbBizPlacePrivateOrder tbBizPlacePrivateOrder) {
//        Predicate<TbBizPlaceUnitSalePlan> predicate = new Predicate<TbBizPlaceUnitSalePlan>() {
//            @Override
//            public boolean apply(TbBizPlaceUnitSalePlan input) {
//                return input.getDate().getTime() == date.getTime();
//            }
//        };
//
//        Collection<TbBizPlaceUnitSalePlan> result = Collections2.filter(tbBizPlaceUnitSalePlans, predicate);
        Collection<TbBizPlaceUnitSalePlan> result = tbBizPlaceUnitSalePlans;
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        BigDecimal price = new BigDecimal(0);
        BigDecimal notMemberPrice = new BigDecimal(0);

        //睡她一毫秒
        try {
            Thread.sleep(1);
        }catch (Exception e){
            e.printStackTrace();
        }

        String orderid = baseService.getBizOrderId(uid);
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = new ArrayList<>();
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : result) {
            // 生成订单明细
            TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
            tbBizPlaceOrderItem.setCreateTime(date);
            tbBizPlaceOrderItem.setUpdateTime(date);
            tbBizPlaceOrderItem.setPlaceOrderId(orderid);
            tbBizPlaceOrderItem.setUnitSalePlanId(null);
            tbBizPlaceOrderItem.setVersion(tbBizPlaceUnitSalePlan.getVersion());
            if (null == tbBizPlaceMemberCard) {
                tbBizPlaceOrderItem.setSalePrice(tbBizPlaceUnitSalePlan.getPrice());
            } else {
                tbBizPlaceOrderItem.setSalePrice(tbBizPlaceUnitSalePlan.getMemberPrice()
                        .multiply(new BigDecimal(discount).divide(new BigDecimal(100))));
            }
            tbBizPlaceOrderItem.setCreateUid(uid);
            tbBizPlaceOrderItem.setSaleId(CommonUtils.createSaleID(tbBizPlaceUnitSalePlan.getPlaceUnitId(), tbBizPlaceUnitSalePlan.getDate(), tbBizPlaceUnitSalePlan.getStartTime(),tbBizPlaceUnitSalePlan.getEndTime()));
            tbBizPlaceOrderItem.setConsumeTime(tbBizPlaceUnitSalePlan.getDate());
            tbBizPlaceOrderItem.setItemUuid(UUIDUtils.createId());
            tbBizPlaceOrderItem.setUseType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
            tbBizPlaceOrderItem.setGoodsId(tbBizPlaceUnitSalePlan.getId());
            tbBizPlaceOrderItem.setGoodsName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
            tbBizPlaceOrderItem.setSurplusGoodsCount(1);
            tbBizPlaceOrderItem.setTotalGoodsCount(1);
            tbBizPlaceOrderItem.setStartTime(tbBizPlaceUnitSalePlan.getStartTime());
            tbBizPlaceOrderItem.setEndTime(tbBizPlaceUnitSalePlan.getEndTime());
            tbBizPlaceOrderItem.setOriginPrice(tbBizPlaceUnitSalePlan.getPrice());
            tbBizPlaceOrderItem.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
            tbBizPlaceOrderItem.setTicketCount(1);
            tbBizPlaceOrderItem.setCategoryId(tbBizPlaceUnitSalePlan.getCategoryId());
            tbBizPlaceOrderItem.setStatus(PlaceConstants.ORDER_PAYED_STATUS.intValue());
            tbBizPlaceOrderItem.setIsGive(PlaceConstants.NO);
            tbBizPlaceOrderItemList.add(tbBizPlaceOrderItem);
            if (null == tbBizPlaceMemberCard) {
                price = price.add(tbBizPlaceUnitSalePlan.getPrice()
                        .multiply(new BigDecimal(discount).divide(new BigDecimal(100))));
            } else {
                price = price.add(tbBizPlaceUnitSalePlan.getMemberPrice()
                        .multiply(new BigDecimal(discount).divide(new BigDecimal(100))));
            }
            notMemberPrice = notMemberPrice.add(tbBizPlaceUnitSalePlan.getPrice());
        }

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        //插入日订单
        TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();
        tbBizPlaceOrder.setPlaceOrderId(orderid);
        tbBizPlaceOrder.setUseType(new Byte(PlaceConstants.PRIVATE_USE_TYPE + ""));
        tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
        tbBizPlaceOrder.setCustomerName(StringUtils.isEmpty(reqBillingInfo.getName()) ? "散客":reqBillingInfo.getName());
        tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
        tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
        tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
        tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
        tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
        tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
        tbBizPlaceOrder.setPaymentTime(tbBizPlacePrivateOrder.getPaymentTime());
        tbBizPlaceOrder.setDebit(notMemberPrice);
        tbBizPlaceOrder.setDate(tbBizPlacePrivateOrder.getDate());
        tbBizPlaceOrder.setEndTime(tbBizPlacePrivateOrder.getEndTime());
        tbBizPlaceOrder.setUpdateTime(date);
        tbBizPlaceOrder.setCreateTime(date);
        tbBizPlaceOrder.setOrderTime(date);
//        tbBizPlaceOrder.setEndTime(date);
//        tbBizPlaceOrder.setPaymentTime(date);
        tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
        tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        tbBizPlaceOrder.setOrderStatusChangeDate(date);
        tbBizPlaceOrder.setParentId(porderid);
        tbBizPlaceOrder.setIsEffective(Constants.IS_ENABLE_FALSE);
        tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
        if (null != tbBizPlaceMemberCard){
            tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
            tbBizPlaceOrder.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
        }else{
            tbBizPlaceOrder.setIsMember(PlaceConstants.NO);
        }

        if (!StringUtils.isEmpty(reqBillingInfo.getExpression())){
            tbBizPlaceOrder.setExpression(reqBillingInfo.getExpression());
        }else{
            tbBizPlaceOrder.setExpression("");
        }
        //今天+7以后订单is_effective=1
        /*try {
            Date finalDate = dateFormat.parse(DateTime.now().plusDays(7).toString("yyyy-MM-dd"));
            Date curDate = dateFormat.parse(dateFormat.format(date));
            if (curDate.getTime() <= finalDate.getTime()) {
                tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);
            }
        } catch (ParseException e) {
            logger.error("日期格式化错误:{}", e.getMessage());
        }*/
        //放开只显示7天的订单
        tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);

        //场馆运营模式
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
        tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(reqBillingInfo.getAdminPayType().toString())){
            tbBizPlaceOrder.setIsType(PlaceConstants.YES);
        }
        Map map = new HashMap();
         //付款对象
            TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
            tbBizPlacePayItem.setPlaceOrderId(orderid);
            tbBizPlacePayItem.setAmount(price);
            tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
            tbBizPlacePayItem.setPayType(reqBillingInfo.getAdminPayType());
            tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(reqBillingInfo.getAdminPayType()).getUnifiedId());
            map.put("pays", tbBizPlacePayItem);
      
        map.put("order", tbBizPlaceOrder);
        map.put("items", tbBizPlaceOrderItemList);
      
        return map;
    }

    private String createID1() {
        UUID randomUUID = UUID.randomUUID();
        String uuid = randomUUID.toString().replaceAll("-", "");
        StringBuffer bf = new StringBuffer();
        bf.append(uuid);
        return bf.toString().toLowerCase();
    }

    private List<TbBizPlaceUnitSalePlan> getTbBizPlaceUnitSalePlan(ReqPlaceSalePlan reqPlaceSalePlan,
                                                                   Date startDate, Date endDate) {
        //循环日期
        Calendar ca = Calendar.getInstance();
        Date curDate = startDate;
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlens = new ArrayList<>();
        while (curDate.compareTo(endDate) <= 0) {
            ca.setTime(curDate);
            //判断周几
            int week = DateUtils.getDayOfWeek(curDate);
            if (StringUtils.isEmpty(reqPlaceSalePlan.getWeek())) {
                return null;
            }
            if (reqPlaceSalePlan.getWeek().contains(week)) {
                TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = new TbBizPlaceUnitSalePlan();
                tbBizPlaceUnitSalePlan.setDate(curDate);
                tbBizPlaceUnitSalePlan.setTimeType(week + "");
                tbBizPlaceUnitSalePlens.add(tbBizPlaceUnitSalePlan);
            }
            ca.add(Calendar.DATE, 1);
            curDate = ca.getTime();
        }
        return tbBizPlaceUnitSalePlens;
    }

    /**
     * 包场生成销售计划
     *
     * @param reqBillingInfo
     * @param startDate
     * @param endDate
     * @return
     */
    private List<TbBizPlaceUnitSalePlan> getTbBizPlaceUnitSalePlanByPlaceBoookAll(ReqBillingInfo reqBillingInfo,
                                                                                  Date startDate, Date endDate) {
        //循环日期
        Calendar ca = Calendar.getInstance();
        Date curDate = startDate;
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlens = new ArrayList<>();
        while (curDate.compareTo(endDate) <= 0) {
            ca.setTime(curDate);
            //判断周几
            int week = DateUtils.getDayOfWeek(curDate);
            if (StringUtils.isEmpty(reqBillingInfo.getWeek())) {
                return null;
            }
            if (reqBillingInfo.getWeek().contains(week)) {
                for (UnitSaleInfo unitSaleInfo : reqBillingInfo.getUnitSaleInfos()) {
                    TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = new TbBizPlaceUnitSalePlan();
                    tbBizPlaceUnitSalePlan.setPlaceUnitId(unitSaleInfo.getUnitId());
                    tbBizPlaceUnitSalePlan.setDate(curDate);
                    tbBizPlaceUnitSalePlan.setTimeType(week + "");
                    tbBizPlaceUnitSalePlan
                            .setStartTime(DateTimeUtils.convertString2Date("HH:mm:ss", unitSaleInfo.getStartTime()));
                    tbBizPlaceUnitSalePlan
                            .setEndTime(DateTimeUtils.convertString2Date("HH:mm:ss", unitSaleInfo.getEndTime()));
                    tbBizPlaceUnitSalePlens.add(tbBizPlaceUnitSalePlan);
                }
            }
            ca.add(Calendar.DATE, 1);
            curDate = ca.getTime();
        }
        /*
        //临时方案（取数据库4周销售计划）
        String[] saleIds = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
        List<String> list = Arrays.asList(saleIds);
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
        criteria.andSaleIdIn(list);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlens = tbBizPlaceUnitSalePlanMapper.selectByExample(example);
        */
        return tbBizPlaceUnitSalePlens;
    }

    public RespBizPlaceServiceInfo getBizPlaceServiceInfo(String name) {
        if (bizPlaceServiceInfoMap.size() <= 0) {
            TbLabelExample tbLabelExample = new TbLabelExample();
            TbLabelExample.Criteria tbLabelCriteria = tbLabelExample.createCriteria();
            tbLabelCriteria.andTypeEqualTo(PlaceConstants.PLACE_LABEL_TYPE);
            List<TbLabel> tbLabelList = tbLabelMapper.selectByExample(tbLabelExample);
            if (CollectionUtils.isNotEmpty(tbLabelList)) {
                for (TbLabel tbLabel : tbLabelList) {
                    RespBizPlaceServiceInfo respBizPlaceServiceInfo = new RespBizPlaceServiceInfo();
                    respBizPlaceServiceInfo.setName(tbLabel.getName());
                    respBizPlaceServiceInfo.setUrl(tbLabel.getIcon());
                    if (tbLabel.getFlagDesc() != null) {
                    	bizPlaceServiceInfoMap.put(tbLabel.getFlagDesc(), respBizPlaceServiceInfo);
					}
                }
            }
        }
        RespBizPlaceServiceInfo respBizPlaceServiceInfo = bizPlaceServiceInfoMap.get(name);
        return respBizPlaceServiceInfo;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean updateTbBizPlaceUnitSalePlan(List<String> placeUnitIds, Byte state, String lockRemarks,String uid) {
        if (CollectionUtils.isEmpty(placeUnitIds)){
            new BizException("场地参数错误,修改失败");
        }
        boolean flag = baseService.updateTbBizPlaceUnitSalePlanEx(placeUnitIds, state, lockRemarks,uid);
        if (!flag) {
            new BizException("修改失败");
        }
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample1 = new TbBizPlaceUnitSalePlanExample();
        tbBizPlaceUnitSalePlanExample1.createCriteria().andSaleIdIn(placeUnitIds);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample1);

        if (tbBizPlaceUnitSalePlans == null
                || tbBizPlaceUnitSalePlans.size() <= 0) {
            new BizException(String.format("PlaceId:%s没有可用的销售计划,修改失败", JSON.toJSONString(tbBizPlaceUnitSalePlans)));
        }

        Integer placeId = tbBizPlaceUnitSalePlans.get(0).getPlaceId();

        if (StringUtils.isEmpty(placeId)){
            new BizException(String.format("PlaceId:%d没有可用的销售计划,修改失败", placeId));
        }
        final Integer finalPlaceId = placeId;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                RedisKey redisKey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY, PlaceConstants.PLACE_SYNC_SOLR_PREFIX );
                Set<Integer> placeIdSet = null;
                if (placeRedisTemplate.exists(redisKey)) {
                    placeIdSet = (Set<Integer>) placeRedisTemplate.get(redisKey);
                    placeIdSet.add(finalPlaceId);
                }else{
                    placeIdSet = Collections.synchronizedSet(new HashSet<Integer>());
                    placeIdSet.add(finalPlaceId);
                }
                if (null != placeIdSet){
                    placeRedisTemplate.set(redisKey, placeIdSet);
                }
            }
        });
        return flag;
    }

    @Override
    public APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> searchH5PlaceList(ReqSearchVo reqSearchVo) {
        //获取有销售计划的场馆ID
        if (!StringUtils.isEmpty(reqSearchVo.getQuerydate())) {
            reqSearchVo.setDate(new Date(reqSearchVo.getQuerydate()));
        }
//        List<Integer> total = this.placeUnitSalePlanMapper.searchCount(reqSearchVo);
        //PageObj<List<RespBizPlaceBaseInfo>> pageObj = new PageObj<>();

        List<Integer> placeIds = this.placeUnitSalePlanMapper.searchByTerm(reqSearchVo);
        if (CollectionUtils.isEmpty(placeIds)) {
            return APIResponse.returnFail("没有可销售的场馆");
        }
        List<RespBizPlaceBaseInfo> result = new ArrayList<>();
        if (reqSearchVo.getCategoryId() != null && reqSearchVo.getCategoryId() != 0) {
            for (Integer placeid : placeIds) {
                result.add(this.placeBaseInfoUtils(placeid, reqSearchVo));
            }
        } else {
            for (Integer placeid : placeIds) {
                result.add(this.placeBaseInfoUtils(placeid));
            }
        }


        if (CollectionUtils.isEmpty(result)) {
            return APIResponse.returnFail("没有可销售的场馆");
        }

        /*PageObj<List<RespBizPlaceBaseInfo>> pageObj = PageObj.create(total.size(), reqSearchVo.getPageNum() / reqSearchVo.getPageSize() + 1,
                reqSearchVo.getPageSize(), result);*/
        PageObj<List<RespBizPlaceBaseInfo>> pageObj = PageObj
                .create(0, reqSearchVo.getPageNum() / reqSearchVo.getPageSize() + 1,
                        reqSearchVo.getPageSize(), result);
        return APIResponse.returnSuccess(pageObj);
    }

    @Override
    public APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> searchByDb(ReqSearchVo reqSearchVo) {
        //获取有销售计划的场馆ID
        if (!StringUtils.isEmpty(reqSearchVo.getQuerydate())) {
            reqSearchVo.setDate(new Date(reqSearchVo.getQuerydate()));
        }
//        List<Integer> total = this.placeUnitSalePlanMapper.searchCount(reqSearchVo);

        List<Integer> placeIds = this.placeUnitSalePlanMapper.searchByDb(reqSearchVo);
        if (CollectionUtils.isEmpty(placeIds)) {
            return APIResponse.returnFail("没有可预定的场馆");
        }
        List<RespBizPlaceBaseInfo> result = new ArrayList<>();
        if (reqSearchVo.getCategoryId() != null && reqSearchVo.getCategoryId() != 0) {
            for (Integer placeid : placeIds) {
                result.add(this.placeBaseInfoUtils(placeid, reqSearchVo));
            }
        } else {
            for (Integer placeid : placeIds) {
                result.add(this.placeBaseInfoUtils(placeid));
            }
        }

        if (CollectionUtils.isEmpty(result)) {
            return APIResponse.returnFail("没有可预定的场馆");
        }
        Integer pageNum = reqSearchVo.getPageNum();
        if (pageNum == null) {
            pageNum = Constants.DEFAULT_PAGE_NUM;
        }

        Integer pageSize = reqSearchVo.getPageSize();
        if (pageSize == null) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        //TODO 数据库搜索排序 8/18
        PageObj<List<RespBizPlaceBaseInfo>> pageObj = PageObj.create(0, pageNum,
                pageSize, result);
        return APIResponse.returnSuccess(pageObj);
    }

    @Override
    public boolean isComment(Integer uid, Integer placeId) {
        ReqIsComment reqIsComment = new ReqIsComment();
        reqIsComment.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        reqIsComment.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqIsComment.setUid(uid);
        reqIsComment.setBusinessId(placeId);
        APIResponse<Boolean> response = this.commentServiceFacade.checkIsComment(reqIsComment);
        if (response.isRet()) {
            return response.getData();
        }
        return false;
    }

    @Override
    public boolean isCollect(Integer uid, Integer placeId) {
        ReqUserCollectQuery reqUserCollectQuery = new ReqUserCollectQuery();
        reqUserCollectQuery.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        reqUserCollectQuery.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqUserCollectQuery.setUserId(uid);
        reqUserCollectQuery.setBusinessId(placeId);
        APIResponse<Boolean> response = this.userCollectServiceFacade.isUserCollect(reqUserCollectQuery);


        if (response.isRet()) {
            return response.getData();
        }
        return false;
    }

    @Override
    public APIResponse<Integer> cancelPlaces(Integer uid, List<Integer> ids) {
        ReqUserCollect reqUserCollect = new ReqUserCollect();
        reqUserCollect.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        reqUserCollect.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqUserCollect.setStatus(Constants.IS_NO);
        reqUserCollect.setUserId(uid);
        APIResponse response = this.userCollectServiceFacade.batchCancelUserCollect(reqUserCollect, ids);
        response.setData(Constants.IS_NO);
        if (response.isRet()) {
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(ids)) {
                RedisKey rediskey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY, uid
                        + PlaceConstants.USER_COLLECT_REDIS_KEY);
                for (int i = 0, len = ids.size(); i < len; i++) {
                    this.placeRedisTemplate.hdel(rediskey.getRedisKey(), ids.get(i).toString().getBytes());
                }
                response.setData(Constants.IS_YES);
            }
        }
        return response;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBilling(ReqBillingInfo reqBillingInfo) throws Exception{
        boolean isScanPayFlag = false;
        if(MerchantClientPayType.getMatchScanPayType().containsKey(reqBillingInfo.getAdminPayType().toString())){//扫码支付方式匹配 update by tim
			isScanPayFlag = true;
		}

        boolean isCompanyFlag = false;//对公转账
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(reqBillingInfo.getAdminPayType().toString())){//对公转账支付方式匹配
            isCompanyFlag = true;
        }
        if (StringUtils.isEmpty(reqBillingInfo.getReceivedAmount())){
            return APIResponse.returnFail("实收金额不能为空！");
        }
        //查询场馆单元销售计划价格
        List<UnitSaleInfo> unitSaleInfos = reqBillingInfo.getUnitSaleInfos();
        if (CollectionUtils.isNotEmpty(unitSaleInfos)) {
            // TODO: 16/6/16 客户端提供修改价格,暂时没用到
        }
        String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
        /*TbBizPlaceUnitSalePlanExample unitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        unitSalePlanExample.createCriteria().andPlaceUnitIdIn(unitids);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(unitSalePlanExample);*/
        List<UnitSalePlan> list = new ArrayList<>();
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();

        for (String unitid : unitids) {
            UnitSalePlan unit = new UnitSalePlan();
            unit.setSaleId(unitid);
            list.add(unit);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(list);

        if (reqPlaceOrderListVo.getPlaceId() == null) {
            reqPlaceOrderListVo.setPlaceId(reqBillingInfo.getPlaceId());
        }

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans =
                placeOrderService.lockTbBizPlaceUnitSalePlanEx(reqPlaceOrderListVo, PlaceConstants.PLACE_LOCk_STATUS);

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            logger.error("没有对应的销售计划:reqBillingInfo:{}", reqBillingInfo.toString());
            return APIResponse.returnFail("没有对应的销售计划");
        }
        //判断是否可销售
        TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = baseService.getNotSellPlan(tbBizPlaceUnitSalePlans);
        if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan)) {
            return APIResponse.returnFail(tbBizPlaceUnitSalePlan.getSaleId() + "不可预订");
        }

        try {
            if (isScanPayFlag){
                APIResponse orderResponse = placeOrderService.saveBillingForScanPay(reqBillingInfo);
                if (orderResponse.isRet() && orderResponse.getData()!=null){
                    TbBizPlaceOrder tbBizPlaceOrder = (TbBizPlaceOrder)orderResponse.getData();
                    PlaceScanOrderPayVo placeScanOrderPayVo = new PlaceScanOrderPayVo();
                    placeScanOrderPayVo.setReceivedAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()));
                    placeScanOrderPayVo.setAdminPayType(reqBillingInfo.getAdminPayType().toString());
                    placeScanOrderPayVo.setScanCode(reqBillingInfo.getScanCode());
                    placeScanOrderPayVo.setTbBizPlaceOrder(tbBizPlaceOrder);
                    placeScanOrderPayVo.setTbBizPlacePrivateOrder(null);
                    return placeOrderService.scanOrderPay(placeScanOrderPayVo);
                } else{
                    return APIResponse.returnFail("扫码开单生成订单失败");
                }
            } else if (isCompanyFlag){
                APIResponse orderResponse = placeOrderService.saveBillingForScanPay(reqBillingInfo);
                if (orderResponse.isRet() && orderResponse.getData()!=null){
                    TbBizPlaceOrder tbBizPlaceOrder = (TbBizPlaceOrder)orderResponse.getData();

                    //插入审核记录
                    PlaceFinanceAuditVo placeFinanceAuditVo = placeOrderUtilService.tbBizPlaceOrder2PlaceFinanceAuditVo(tbBizPlaceOrder);
                    if (!StringUtils.isEmpty(placeFinanceAuditVo)){
                        financeService.createAuditRecord(placeFinanceAuditVo);
                    }

                    //打印小票
                    PlacePrintVo placePrintVo = new PlacePrintVo();
                    placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                    placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BILLING);
                    placePrintVo.setIsMember(PlaceConstants.NO);
                    return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
                } else {
                    return APIResponse.returnFail("对公转账生成订单失败");
                }
            } else {
                return placeOrderService.saveBilling(reqBillingInfo);
            }
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBillingPlus(ReqBillingInfo reqBillingInfo) throws Exception{
        if (StringUtils.isEmpty(reqBillingInfo.getReceivedAmount())){
            return APIResponse.returnFail("实收金额不能为空！");
        }

        if (StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())){
            return APIResponse.returnFail("saleId参数错误");
        }

        boolean isScanPayFlag = false;
        if(MerchantClientPayType.getMatchScanPayType().containsKey(reqBillingInfo.getAdminPayType().toString())){//扫码支付方式匹配 update by tim
            isScanPayFlag = true;
        }

        boolean isCompanyFlag = false;//对公转账
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(reqBillingInfo.getAdminPayType().toString())){//对公转账支付方式匹配
            isCompanyFlag = true;
        }

        String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
        /*TbBizPlaceUnitSalePlanExample unitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        unitSalePlanExample.createCriteria().andPlaceUnitIdIn(unitids);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(unitSalePlanExample);*/
        List<UnitSalePlan> list = new ArrayList<>();
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();

        for (String unitid : unitids) {
            UnitSalePlan unit = new UnitSalePlan();
            unit.setSaleId(unitid);
            list.add(unit);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(list);
        if (reqBillingInfo.getPlaceId() != null) {
            reqPlaceOrderListVo.setPlaceId(reqBillingInfo.getPlaceId());
        }

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = placeUnitSalePlanMapper.selectByPrimaryKeyList(reqPlaceOrderListVo);
        //判断是否可销售
        TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = baseService.getNotSellPlan(tbBizPlaceUnitSalePlanList);
        if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan)) {
            return APIResponse.returnFail(tbBizPlaceUnitSalePlan.getSaleId() + "不可预订");
        }

        try {
            placeOrderService.lockTbBizPlaceUnitSalePlanExPlus(reqPlaceOrderListVo);
        } catch (Exception e){
            throw e;
        }


        try {
            if (isScanPayFlag){
                APIResponse orderResponse = placeOrderService.saveBillingForScanPay(reqBillingInfo);
                if (orderResponse.isRet() && orderResponse.getData()!=null){
                    TbBizPlaceOrder tbBizPlaceOrder = (TbBizPlaceOrder)orderResponse.getData();
                    PlaceScanOrderPayVo placeScanOrderPayVo = new PlaceScanOrderPayVo();
                    placeScanOrderPayVo.setReceivedAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()));
                    placeScanOrderPayVo.setAdminPayType(reqBillingInfo.getAdminPayType().toString());
                    placeScanOrderPayVo.setScanCode(reqBillingInfo.getScanCode());
                    placeScanOrderPayVo.setTbBizPlaceOrder(tbBizPlaceOrder);
                    placeScanOrderPayVo.setTbBizPlacePrivateOrder(null);
                    return placeOrderService.scanOrderPay(placeScanOrderPayVo);
                } else{
                    throw new BizException(orderResponse.getErrmsg());
                }
            } else if (isCompanyFlag){
                APIResponse orderResponse = placeOrderService.saveBillingForScanPay(reqBillingInfo);
                if (orderResponse.isRet() && orderResponse.getData()!=null){
                    TbBizPlaceOrder tbBizPlaceOrder = (TbBizPlaceOrder)orderResponse.getData();

                    //插入审核记录
                    PlaceFinanceAuditVo placeFinanceAuditVo = placeOrderUtilService.tbBizPlaceOrder2PlaceFinanceAuditVo(tbBizPlaceOrder);
                    if (!StringUtils.isEmpty(placeFinanceAuditVo)){
                        financeService.createAuditRecord(placeFinanceAuditVo);
                    }

                    //打印小票
                    PlacePrintVo placePrintVo = new PlacePrintVo();
                    placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                    placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BILLING);
                    placePrintVo.setIsMember(PlaceConstants.NO);
                    return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
                } else {
                    throw new BizException(orderResponse.getErrmsg());
                }
            } else {
                APIResponse response = placeOrderService.saveBilling(reqBillingInfo);
                if (response.isRet()){
                    return response;
                } else {
                    throw new BizException(response.getErrmsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("场地已被预订");
        }
    }

    /**
     * 商家端包场支付
     *
     * @param reqBillingInfo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBookAll(ReqBillingInfo reqBillingInfo) throws Exception {
        boolean isScanPayFlag = false;
		if(MerchantClientPayType.getMatchScanPayType().containsKey(reqBillingInfo.getAdminPayType().toString())){//扫码支付方式匹配 update by tim
			isScanPayFlag = true;
		}

        boolean isCompanyFlag = false;//对公转账
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(reqBillingInfo.getAdminPayType().toString())){//对公转账支付方式匹配
            isCompanyFlag = true;
        }
        System.out.println(JSON.toJSON(reqBillingInfo));
        // 1.查询客户端返回时间段 周几 `place_id` `place_unit_id`  根据销售模板计算销售计划的总数
        // 2.判断有的就更新  没有就插入
        if (!StringUtils.isEmpty(reqBillingInfo.getWeeks())) {
            String[] ids1 = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getWeeks(), ",");
            List<String> list = Arrays.asList(ids1);
            List<Integer> weekList = new ArrayList<>();
            for (String weekstr : list) {
                weekList.add(Integer.parseInt(weekstr));
            }
            reqBillingInfo.setWeek(weekList);
        }

        //=======校验是否有存在不可售的销售计划（防止超卖情况） 开始=========
        if (CollectionUtils.isEmpty(reqBillingInfo.getUnitSaleInfos())){
            return APIResponse.returnFail("场地信息必传");
        }
        PlaceBookAllCheckVo placeBookAllCheckVo = new PlaceBookAllCheckVo();
        placeBookAllCheckVo.setPlaceId(reqBillingInfo.getPlaceId());
        placeBookAllCheckVo.setCategoryId(reqBillingInfo.getCategoryId());
        placeBookAllCheckVo.setEndDate(DateUtils.transferLongToDate(reqBillingInfo.getEndDate()));
        placeBookAllCheckVo.setStartDate(DateUtils.transferLongToDate(reqBillingInfo.getStartDate()));
        placeBookAllCheckVo.setTimeTypeList(reqBillingInfo.getWeek());
        
        List<UnitSaleInfo> unitSaleInfoList = new ArrayList<>();
        for (UnitSaleInfo unitSaleInfo : reqBillingInfo.getUnitSaleInfos()){
            unitSaleInfoList.add(unitSaleInfo);
        }
        placeBookAllCheckVo.setPlaceUnitSaleInfoList(unitSaleInfoList);
        
        List<String> tbSaleIds = placeBlockBookingOrderMapper.checkBookAllOrder(placeBookAllCheckVo);
        List<String> reqSaleIdList = null;
        if (!StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())) {
            String[] saleIds = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
            reqSaleIdList = Arrays.asList(saleIds);
        }
        if (CollectionUtils.isEmpty(reqSaleIdList)){
            return APIResponse.returnFail("saleIds必传");
        }
        
        tbSaleIds.retainAll(reqSaleIdList);//取交集
        logger.error(tbSaleIds.toString()+"场地已被预定");
        
        if (CollectionUtils.isNotEmpty(tbSaleIds)){
            return APIResponse.returnFail("场地已被预定");
        }
        
        //=======校验是否有存在不可售的销售计划（防止超卖情况） 结束=========

        if (!StringUtils.isEmpty(reqBillingInfo.getUnitIds())) {
            String[] unitIds = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getUnitIds(), ",");
            List<String> unitList = Arrays.asList(unitIds);
            List<Integer> unitIdList = new ArrayList<>();
            for (String unitstr : unitList) {
                unitIdList.add(Integer.parseInt(unitstr));
            }
            reqBillingInfo.setUnitId(unitIdList);
        }
        
        List<TbBizPlaceUnitSalePlan> resultList = new ArrayList<>();
        logger.debug("====================开始增加销售计划");
        //包场增加销售计划
        Date startDate = new Date(reqBillingInfo.getStartDate());
        Date endDate = new Date(reqBillingInfo.getEndDate());

        //获取日期内符合星期的销售列表
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = getTbBizPlaceUnitSalePlanByPlaceBoookAll(reqBillingInfo,
                startDate, endDate);
        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return APIResponse.returnFail("选择的星期不在日期范围内");
        }

        //获取销售计划模板
        List<String> types = new ArrayList<>();
        for (Integer type : reqBillingInfo.getWeek()) {
            types.add(type + "");
        }
        TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
        TbBizPlaceUnitSalePlanMainExample.Criteria mainCriteria = tbBizPlaceUnitSalePlanMainExample.createCriteria();
        mainCriteria.andIsEffectiveEqualTo(Constants.IS_ENABLE_TRUE).andPlaceIdEqualTo(reqBillingInfo.getPlaceId())
                .andPlaceUnitIdIn(reqBillingInfo.getUnitId())
                .andCategoryIdEqualTo(reqBillingInfo.getCategoryId()).andTimeTypeIn(types);
        List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMains = tbBizPlaceUnitSalePlanMainMapper
                .selectByExample(tbBizPlaceUnitSalePlanMainExample);
        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMains)) {
            logger.error("==========================没有销售计划模板 ReqPlaceSalePlan:{}",
                    JSON.toJSONString(reqBillingInfo));
            RespBizCodeInfo respBizCodeInfo = new RespBizCodeInfo();
            respBizCodeInfo.setSuccess(false);
            respBizCodeInfo.setGetCode(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getCode());
            respBizCodeInfo.setGetId(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getId());
            respBizCodeInfo.setGetLabel(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getLabel());
            return APIResponse.returnSuccess(respBizCodeInfo);
        }

        // 查询该场馆的所有的组合场信息
        List<PlaceCombinedUnitVo> allCUs = placeUCService.getCombinedUnits(reqBillingInfo.getPlaceId(), reqBillingInfo.getCategoryId(), null);
        Map<Integer, PlaceCombinedUnitVo> CUMap = new HashMap();
        if (allCUs != null && allCUs.size() > 0) {
            for (PlaceCombinedUnitVo cu : allCUs) {
                if (!CUMap.containsKey(cu.getId())) {
                    CUMap.put(cu.getId(), cu);
                }
            }
        }

        for (TbBizPlaceUnitSalePlan tbUnitSalePlan1 : tbBizPlaceUnitSalePlans) {
            for (TbBizPlaceUnitSalePlanMain tbMain : tbBizPlaceUnitSalePlanMains) {
                //去除销售计划模板中没有的数据
                if (tbUnitSalePlan1.getPlaceUnitId().intValue() == tbMain.getPlaceUnitId().intValue() &&
                        tbUnitSalePlan1.getTimeType().equals(tbMain.getTimeType())
                        && (tbUnitSalePlan1.getStartTime().equals(tbMain.getStartTime())
                        && tbUnitSalePlan1.getEndTime().equals(tbMain.getEndTime()))) {
                    TbBizPlaceUnitSalePlan tbUnitSalePlan = new TbBizPlaceUnitSalePlan();
                    BeanUtils.copyProperties(tbUnitSalePlan1, tbUnitSalePlan);
                    tbUnitSalePlan.setPlaceId(tbMain.getPlaceId());
                    tbUnitSalePlan.setPlaceUnitId(tbMain.getPlaceUnitId());
                    tbUnitSalePlan.setCategoryId(tbMain.getCategoryId());
                    tbUnitSalePlan.setSalePlanMainId(tbMain.getId());
                    tbUnitSalePlan.setSaleId(CommonUtils.createSaleID(tbMain.getPlaceUnitId(), tbUnitSalePlan1.getDate(), tbMain.getStartTime(),tbMain.getEndTime()));
                    tbUnitSalePlan.setPlaceUnitName(tbMain.getPlaceUnitName());
                    tbUnitSalePlan.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                    tbUnitSalePlan.setStartTime(tbMain.getStartTime());
                    tbUnitSalePlan.setEndTime(tbMain.getEndTime());
                    tbUnitSalePlan.setPrice(tbMain.getPrice());
                    tbUnitSalePlan.setMemberPrice(tbMain.getMemberPrice());
                    tbUnitSalePlan.setIsEffective(Constants.IS_ENABLE_TRUE);
                    tbUnitSalePlan.setVersion(tbMain.getVersion());
                    tbUnitSalePlan.setUnitType(tbMain.getUnitType());   // 确定场地类型
                    if (tbMain.getBundleNo() != null){
                        if (tbMain.getBundleNo() == 0){
                            tbUnitSalePlan.setBundleNo(0);
                        } else {
                            String bundleNo = tbMain.getPlaceUnitId()+""+tbMain.getBundleNo();
                            tbUnitSalePlan.setBundleNo(Integer.valueOf(bundleNo));
                        }
                    }
                    if (UNIT_TYPE_COMBINE.equals(tbUnitSalePlan.getUnitType())) {
                        PlaceCombinedUnitVo thisCU = CUMap.get(tbMain.getPlaceUnitId());
                        if (thisCU == null || thisCU.getBaseUnits() == null) {
                            continue;
                        }

                        String baseUnits = thisCU.getBaseUnits();
                        List<Integer> baseUnitIds = PlaceUtil.splitIds(baseUnits);
                        if (baseUnitIds == null || baseUnitIds.size() <= 0) {
                            continue;
                        }

                        List<String> saleIds = new ArrayList<>();
                        for (Integer buId : baseUnitIds) {
                            saleIds.add(CommonUtils.createSaleID(buId, tbUnitSalePlan1.getDate(), tbMain.getStartTime(),tbMain.getEndTime()));
                        }
                        tbUnitSalePlan.setSubSaleplans(StringUtil.join("|", saleIds));
                    }

                    resultList.add(tbUnitSalePlan);
                }
            }
        }
        Map<String, TbBizPlaceUnitSalePlan> resultMap = new HashMap();
        //去除重复销售计划
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : resultList) {
            if (!resultMap.containsKey(tbBizPlaceUnitSalePlan.getSaleId())) {
                resultMap.put(tbBizPlaceUnitSalePlan.getSaleId(), tbBizPlaceUnitSalePlan);
            }
        }
        List<TbBizPlaceUnitSalePlan> districtList = new ArrayList<>();
        for (Map.Entry<String, TbBizPlaceUnitSalePlan> entry : resultMap.entrySet()) {
            districtList.add(entry.getValue());
        }

        // 不要有重叠
        APIResponse apiResponse = placeOrderService.salePlansVerification(districtList);
        if (apiResponse != null) {
            return APIResponse.returnFail("要包场的场地间存在组合-子场重叠");
        }

        if (isScanPayFlag){
            if (addTbUnitSalePlanForScanPay(districtList)){
                TbBizPlacePrivateOrder tbBizPlacePrivateOrder = createBookForScanPay(reqBillingInfo,districtList);//创建订单
                if (tbBizPlacePrivateOrder!=null){
                    PlaceScanOrderPayVo placeScanOrderPayVo = new PlaceScanOrderPayVo();

                    placeScanOrderPayVo.setReceivedAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()));
                    placeScanOrderPayVo.setAdminPayType(reqBillingInfo.getAdminPayType().toString());
                    placeScanOrderPayVo.setScanCode(reqBillingInfo.getScanCode());
                    placeScanOrderPayVo.setTbBizPlaceOrder(null);
                    placeScanOrderPayVo.setTbBizPlacePrivateOrder(tbBizPlacePrivateOrder);

                    return placeOrderService.scanOrderPay(placeScanOrderPayVo);//扫码去支付
                }else{
                    return APIResponse.returnFail("扫码支付包场生成订单异常");
                }
            }else{
                return APIResponse.returnFail("扫码支付包场锁定失败");
            }
        } else if (isCompanyFlag){
            if (addTbUnitSalePlanForScanPay(districtList)){
                TbBizPlacePrivateOrder tbBizPlacePrivateOrder = createBookForScanPay(reqBillingInfo,districtList);//创建订单
                if (tbBizPlacePrivateOrder!=null){

                    TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();
                    BeanUtils.copyProperties(tbBizPlacePrivateOrder,tbBizPlaceOrder);
                    //插入审核记录
                    PlaceFinanceAuditVo placeFinanceAuditVo = placeOrderUtilService.tbBizPlaceOrder2PlaceFinanceAuditVo(tbBizPlaceOrder);
                    if (!StringUtils.isEmpty(placeFinanceAuditVo)){
                        financeService.createAuditRecord(placeFinanceAuditVo);
                    }

                    //打印小票
                    PlacePrintVo placePrintVo = new PlacePrintVo();
                    placePrintVo.setIsMember(PlaceConstants.NO);
                    placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
                    placePrintVo.setPlacePrivateOrderId(tbBizPlacePrivateOrder.getPlaceOrderId());
                    return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
                }else{
                    return APIResponse.returnFail("对公转账包场生成订单异常");
                }
            }else{
                return APIResponse.returnFail("对公转账包场锁定失败");
            }
        } else{
            APIResponse response = this.createBook(reqBillingInfo, districtList);
            if (response.isRet() && addTbUnitSalePlan(districtList)){
                TbBizPlacePrivateOrder tbBizPlacePrivateOrder = (TbBizPlacePrivateOrder)response.getData();
                PlacePrintVo placePrintVo = new PlacePrintVo();
                placePrintVo.setIsMember(PlaceConstants.NO);
                placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
                placePrintVo.setPlacePrivateOrderId(tbBizPlacePrivateOrder.getPlaceOrderId());
                return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
            }else{
                return APIResponse.returnFail("包场失败");
            }
        }
    }

    /**
     * 商家端开单预订
     *
     * @param reqBillingInfo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBook(ReqBillingInfo reqBillingInfo) {
        //查询场馆单元销售计划价格
        List<UnitSaleInfo> unitSaleInfos = reqBillingInfo.getUnitSaleInfos();
        if (CollectionUtils.isNotEmpty(unitSaleInfos)) {
            // TODO: 16/6/16 客户端提供修改价格,暂时没用到
        }
        String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
        /*TbBizPlaceUnitSalePlanExample unitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        unitSalePlanExample.createCriteria().andPlaceUnitIdIn(unitids);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(unitSalePlanExample);*/
        List<UnitSalePlan> list = new ArrayList<>();
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();

        for (String unitid : unitids) {
            UnitSalePlan unit = new UnitSalePlan();
            unit.setSaleId(unitid);
            list.add(unit);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(list);

        // 如果是组合场地要判断子场地的销售情况
        if (reqPlaceOrderListVo.getPlaceId() == null) {
            reqPlaceOrderListVo.setPlaceId(reqBillingInfo.getPlaceId());
        }
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans =
                placeOrderService.lockTbBizPlaceUnitSalePlanEx(reqPlaceOrderListVo, PlaceConstants.PLACE_LOCk_STATUS);

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            logger.error("没有对应的销售计划:reqBillingInfo:{}", reqBillingInfo.toString());
            return APIResponse.returnFail("没有对应的销售计划,或者销售计划有重叠不可预定");
        }
        //判断是否可销售
        TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = baseService.getNotSellPlan(tbBizPlaceUnitSalePlans);
        if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan)) {
            return APIResponse.returnFail(tbBizPlaceUnitSalePlan.getSaleId() + "不可预订");
        }
        //插入数据库
        logger.debug("===================开始插入数据库:ReqBillingInfo:{}", JSON.toJSONString(reqBillingInfo));
        if (placeOrderService.saveBook(reqBillingInfo)) {
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("预订失败");
    }

    /**
     * 商家端开单预订
     *
     * @param reqBillingInfo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBookPlus(ReqBillingInfo reqBillingInfo) throws Exception{
        if (StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())){
            return APIResponse.returnFail("saleId参数错误");
        }

        String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");

        List<UnitSalePlan> list = new ArrayList<>();
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();

        for (String unitid : unitids) {
            UnitSalePlan unit = new UnitSalePlan();
            unit.setSaleId(unitid);
            list.add(unit);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(list);
        if (reqBillingInfo.getPlaceId() != null) {
            reqPlaceOrderListVo.setPlaceId(reqBillingInfo.getPlaceId());
        }

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = placeUnitSalePlanMapper.selectByPrimaryKeyList(reqPlaceOrderListVo);
        //判断是否可销售
        TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = baseService.getNotSellPlan(tbBizPlaceUnitSalePlanList);
        if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan)) {
            return APIResponse.returnFail(tbBizPlaceUnitSalePlan.getSaleId() + "不可预订");
        }

        try {
            placeOrderService.lockTbBizPlaceUnitSalePlanExPlus(reqPlaceOrderListVo);
        } catch (Exception e){
            throw e;
        }

        try {
            APIResponse apiResponse = placeOrderService.saveBookPlus(reqBillingInfo);
            if (apiResponse.isRet()){
                return apiResponse;
            } else {
                throw new BizException(apiResponse.getErrmsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("预订生成订单失败");
        }
    }

    /**
     * 商家端包场子订单取消预订
     *
     * @param reqPlaceOrderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBlockCancelBook(String reqPlaceOrderId) {
        if (!StringUtils.isEmpty(reqPlaceOrderId)) {
            boolean result = placeOrderService.cancelBlockBook(reqPlaceOrderId);
            if (result){
                return APIResponse.returnFail("订单取消成功");
            } else {
                throw new BizException("订单取消失败");
            }
        } else {
            return APIResponse.returnFail("取消预订失败");
        }
    }
    
    /**
     * 商家端开单取消预订
     *
     * @param reqPlaceOrderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeCancelBook(String reqPlaceOrderId) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(reqPlaceOrderId)){
            return APIResponse.returnFail("参数订单Id不能为空");
        }
        try {
            boolean result = placeOrderService.cancelBook(reqPlaceOrderId);
            if (result){
                return APIResponse.returnSuccess("取消预订成功");
            } else {
                throw new BizException("取消预订失败");
            }
        } catch (Exception e){
            throw new BizException("取消预订失败");
        }
    }
    
    /**
     * 商家端开单支付
     *
     * @param reqPlaceOrderId
     * @return
     */
    @Override
    public APIResponse<?> placePay(String reqPlaceOrderId,
                                   Integer adminPayType,
                                   String receivedAmount,
                                   String memo,
                                   String expression,
                                   String scanCode) throws Exception {
        boolean isScanPayFlag = false; 
        if(MerchantClientPayType.getMatchScanPayType().containsKey(adminPayType.toString())){
        	isScanPayFlag = true;
        	if(!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){//扫码支付方式匹配 update by tim
        		if (StringUtils.isEmpty(scanCode)){//微信、支付宝必须输入支付码
                    return APIResponse.returnFail("支付失败-支付码必需");
                }
        	}
 
		}
        boolean isCompanyFlag = false;//对公转账
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(adminPayType.toString())){//对公转账支付方式匹配
            isCompanyFlag = true;
        }
        if (StringUtils.isEmpty(reqPlaceOrderId)) {
            return APIResponse.returnFail("支付失败-没有此订单");
        }

        /**
         * 需求变更：1.支付中心生成订单，不允许修改金额，只能修改支付方式
         *           2.其他既能修改金额，又能修改支付方式
         */
        try {
            if (isScanPayFlag){
                TbBizPlaceOrder tbBizPlaceOrder = getTbBizPlaceOrderByOrderNo(reqPlaceOrderId,adminPayType,receivedAmount,memo,expression);
                PlaceScanOrderPayVo placeScanOrderPayVo = new PlaceScanOrderPayVo();
                placeScanOrderPayVo.setReceivedAmount(new BigDecimal(receivedAmount));
                placeScanOrderPayVo.setAdminPayType(adminPayType.toString());
                placeScanOrderPayVo.setScanCode(scanCode);
                placeScanOrderPayVo.setTbBizPlaceOrder(tbBizPlaceOrder);
                placeScanOrderPayVo.setTbBizPlacePrivateOrder(null);
                //包场订单现在改为支持先预定，后按单个订单支付
//                if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING) && !StringUtils.isEmpty(tbBizPlaceOrder.getParentId())){
//                    return APIResponse.returnFail("包场订单不支持单个支付！");
//                }
                return placeOrderService.scanOrderPay(placeScanOrderPayVo);
            } else if (isCompanyFlag){
                TbBizPlaceOrder tbBizPlaceOrder = getTbBizPlaceOrderByOrderNo(reqPlaceOrderId,adminPayType,receivedAmount,memo,expression);

                //插入审核记录
                PlaceFinanceAuditVo placeFinanceAuditVo = placeOrderUtilService.tbBizPlaceOrder2PlaceFinanceAuditVo(tbBizPlaceOrder);
                if (!StringUtils.isEmpty(placeFinanceAuditVo)){
                    financeService.createAuditRecord(placeFinanceAuditVo);
                }

                //打印小票
                PlacePrintVo placePrintVo = new PlacePrintVo();
                placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                placePrintVo.setBusinessType(tbBizPlaceOrder.getUseType());
                placePrintVo.setIsMember(tbBizPlaceOrder.getIsMember());
                return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
            } else {
                return placeOrderService.savePay(reqPlaceOrderId, adminPayType, receivedAmount, memo,expression);
            }
        }  catch (Exception e){
        return APIResponse.returnFail(e.getMessage());
     }
    }
    
    
    /**
     * 商家端包场子订单支付
     *
     * @param reqPlaceOrderId
     * @return
     */
    @Override
    public APIResponse<?> placeBlockPay(String reqPlaceOrderId,
                                   Integer adminPayType,
                                   String receivedAmount,
                                   String memo,
                                   String expression,
                                   String scanCode) throws Exception {
        boolean isScanPayFlag = false; 
        if(MerchantClientPayType.getMatchScanPayType().containsKey(adminPayType.toString())){
        	isScanPayFlag = true;
        	if(!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){//扫码支付方式匹配 update by tim
        		if (StringUtils.isEmpty(scanCode)){//微信、支付宝必须输入支付码
                    return APIResponse.returnFail("支付失败-支付码必需");
                }
        	}
		}

        boolean isCompanyFlag = false;//对公转账
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(adminPayType.toString())){//对公转账支付方式匹配
            isCompanyFlag = true;
        }
        if (StringUtils.isEmpty(reqPlaceOrderId)) {
            return APIResponse.returnFail("支付失败-没有此订单");
        }
        try {
            if (isScanPayFlag){
                TbBizPlaceOrder tbBizPlaceOrder = getTbBizPlaceOrderByOrderNo(reqPlaceOrderId,adminPayType,receivedAmount,memo,expression);
                PlaceScanOrderPayVo placeScanOrderPayVo = new PlaceScanOrderPayVo();
                placeScanOrderPayVo.setReceivedAmount(new BigDecimal(receivedAmount));
                placeScanOrderPayVo.setAdminPayType(adminPayType.toString());
                placeScanOrderPayVo.setScanCode(scanCode);
                placeScanOrderPayVo.setTbBizPlaceOrder(tbBizPlaceOrder);
                placeScanOrderPayVo.setTbBizPlacePrivateOrder(null);
                //包场订单现在改为支持先预定，后按单个订单支付
//                if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING) && !StringUtils.isEmpty(tbBizPlaceOrder.getParentId())){
//                    return APIResponse.returnFail("包场订单不支持单个支付！");
//                }
                return placeOrderService.scanBlockOrderPay(placeScanOrderPayVo);
            }else if (isCompanyFlag){
                TbBizPlaceOrder tbBizPlaceOrder = getTbBizPlaceOrderByOrderNo(reqPlaceOrderId,adminPayType,receivedAmount,memo,expression);

                //插入审核记录
                PlaceFinanceAuditVo placeFinanceAuditVo = placeOrderUtilService.tbBizPlaceOrder2PlaceFinanceAuditVo(tbBizPlaceOrder);
                if (!StringUtils.isEmpty(placeFinanceAuditVo)){
                    financeService.createAuditRecord(placeFinanceAuditVo);
                }

                //打印小票
                PlacePrintVo placePrintVo = new PlacePrintVo();
                placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
                placePrintVo.setBusinessType(tbBizPlaceOrder.getUseType());
                placePrintVo.setIsMember(tbBizPlaceOrder.getIsMember());
                return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
            }else{
                return placeOrderService.saveBlockPay(reqPlaceOrderId, adminPayType, receivedAmount, memo,expression);
            }
        }  catch (Exception e){
        return APIResponse.returnFail(e.getMessage());
    }

    }

    private TbBizPlaceOrder getTbBizPlaceOrderByOrderNo(String placeOrderId,Integer adminPayType,String receivedAmount,String memo,String expression){
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        if (CollectionUtils.isEmpty(tbBizPlaceOrders)){
            return null;
        }
        if (tbBizPlaceOrders.get(0).getOrderStatus() > 1){
            throw new BizException("订单状态已更新,无法支付！");
        }

        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(tbBizPlaceOrders.get(0).getPlaceOrderId());
        List<TbBizPlacePayItem> tbBizPlacePayItems = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);

        BigDecimal payAmount = new BigDecimal(receivedAmount);

        if (!org.apache.commons.collections.CollectionUtils.isEmpty(tbBizPlacePayItems)){
            //由非对公转账切换到对公转账 需要提交审核
            if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(tbBizPlacePayItems.get(0).getPayType().toString())
                    && PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(adminPayType.toString())){
                // TODO: 2017/5/10 提交审核
                throw new BizException("订单已提交财务审核！");
            }
        }
        
        //订单明细
        //根据placeOrderId拿到placeOrderItem
        TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
        itemExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this.tbBizPlaceOrderItemMapper.selectByExample(itemExample);
        if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
            throw new BizException("订单明细为null");
        }
        BigDecimal price = new BigDecimal(0);
        for(TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
            price = price.add(tbBizPlaceOrderItem.getSalePrice());
        }

        tbBizPlaceOrders.get(0).setExpression(expression);
        tbBizPlaceOrders.get(0).setDescrible(memo);
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){
            tbBizPlaceOrders.get(0).setIsType(PlaceConstants.YES);
        }
        tbBizPlaceOrderMapper.updateByExampleSelective(tbBizPlaceOrders.get(0),tbBizPlaceOrderExample);

        List<TbBizPlaceOrderItem> adjustTbBizPlaceOrderItems = iBaseService.adjustOrderItemPrice(payAmount,tbBizPlaceOrderItems,price);
        for (TbBizPlaceOrderItem item : adjustTbBizPlaceOrderItems){
            tbBizPlaceOrderItemMapper.updateByPrimaryKeySelective(item);
        }
       
        if (tbBizPlacePayItems.size()==1){ 
        	boolean flag=true;
        	//update by tim 变更原先额度，重新生成订单
        	if(PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())
                    || PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())){//变更原先银联支付额度，重新生成订单
        		int result = tbBizPlacePayItems.get(0).getAmount().compareTo(payAmount);
                // 价格有变更
                if (result != 0) {
                	flag=false;
                }
        	}
        	
        	if(flag){
        		 tbBizPlacePayItems.get(0).setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
                 tbBizPlacePayItems.get(0).setPayType(adminPayType);
                 tbBizPlacePayItems.get(0).setAmount(payAmount);
                 tbBizPlacePayItemMapper.updateByPrimaryKeySelective(tbBizPlacePayItems.get(0));
        	}else{
        		return generatePosUMNewOrder(adminPayType,payAmount,placeOrderId);//针对pos银联重新生成新订单
        	}
        }
        if (tbBizPlacePayItems.size()==0){
        	if(!adminPayType.toString().equals(PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY)){//非pos生成支付明细
        		 TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
                 tbBizPlacePayItem.setPlaceOrderId(placeOrderId);
                 tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
                 tbBizPlacePayItem.setPayType(adminPayType);
                 tbBizPlacePayItem.setAmount(payAmount);
                 tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
                 tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem);	
        	}else{
        		//update by tim 新增银联支付方式：变更原先额度，重新生成订单
            	if(org.apache.commons.lang3.StringUtils.isNoneEmpty(tbBizPlaceOrders.get(0).getOrderNo())){
            		int result = price.compareTo(payAmount);
                    // 价格有变更
                    if (result!=0) {
                    	return generatePosUMNewOrder(adminPayType,payAmount,placeOrderId);//针对pos银联重新生成新订单
                    }
            		
            	}
            	
        	}
           
        }
        return tbBizPlaceOrders.get(0);
    }

    /**
     * 对开单散客付款、门票散客支付、商品售卖散客支付，包场散客付款，重新生成订单
     * 	 @param adminPayType
	 * @param payAmount
	 */
	private TbBizPlaceOrder generatePosUMNewOrder(Integer adminPayType, BigDecimal payAmount,String placeOrderId) {
		//订单
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		TbBizPlaceOrder placeOrder=tbBizPlaceOrders.get(0);
		//明细
		 TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
		 tbBizPlaceOrderItemExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
		 List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
		
		switch (placeOrder.getUseType()) {
		case 0:
			return super.generatePlaceBillingOrder(placeOrder,tbBizPlaceOrderItemList,adminPayType,payAmount,placeOrderId);
		case 3:
			return super.generatePlaceBillingOrder(placeOrder,tbBizPlaceOrderItemList,adminPayType,payAmount,placeOrderId);
	    case 2:
			return super.generateTicketOrder(placeOrder,tbBizPlaceOrderItemList,adminPayType, payAmount,placeOrderId);
	    case 4:
	        return super.generateGoodsOrder(placeOrder,tbBizPlaceOrderItemList,adminPayType, payAmount,placeOrderId);
	    case 1:
	    	return super.generatePlaceBookAllOrder(placeOrder,tbBizPlaceOrderItemList,adminPayType,payAmount,placeOrderId);
		}
		return null;
	}


	@Override
    public APIResponse<PageObj<List<RespUserBizPlaceOrderInfo>>> userPlaceOrder(Map map) {
        Integer uid = MapUtils.getInteger(map, "uid");
        Integer sourceType = MapUtils.getInteger(map, "sourceType");
        String mobile = MapUtils.getString(map, "mobile");
        Integer pageNum = MapUtils.getInteger(map, "pageNum", 0);
        Integer pageSize = MapUtils.getInteger(map, "pageSize", 10);
        Integer opType = MapUtils.getInteger(map, "opType");
        //String token = MapUtils.getString(map, "token");
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer) httpServletRequest.getAttribute("uid");
        uid = userId;
        Integer orderStatus = MapUtils.getInteger(map, "orderStatus");
        Integer isEnable = MapUtils.getInteger(map, "isEnable", 0);

        /*if (!StringUtils.isEmpty(opType) && StringUtils.isEmpty(token)) {
            return APIResponse.returnFail(PlaceErrorCodeEnum.TOKEN_EXPIRED);
        }

        if (!StringUtils.isEmpty(opType)) {
            uid = userServiceFacade.getUserIdByToken(token);
            if (StringUtils.isEmpty(uid)) {
                return APIResponse.returnFail(PlaceErrorCodeEnum.TOKEN_EXPIRED);
            }
        }*/
        if (!StringUtils.isEmpty(sourceType)) {
            if (sourceType < 1 || sourceType > 4) {//超出订单类型
                return APIResponse.returnSuccess(null);
            }
        }
        if (StringUtils.isEmpty(opType) && StringUtils.isEmpty(mobile) && StringUtils.isEmpty(uid)) {
            return APIResponse.returnSuccess(null);
        }
        PageObj<List<RespUserBizPlaceOrderInfo>> pageObj = this.baseService
                .getRespBizPlaceOrderInfoByUid(mobile, uid, pageNum, pageSize, opType, sourceType, orderStatus, isEnable);
        if (StringUtils.isEmpty(pageObj)) {
            logger.debug("=============================Uid:{} =====没有场馆订单", uid);
            return APIResponse.returnSuccess(null);
        }
        return APIResponse.returnSuccess(pageObj);
    }


    @Override
    public APIResponse<RespActivityOrMatchDetail> activityOrMatchDetail(ReqActivityOrMatchDetail reqActivityOrMatchDetail) {
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer) httpServletRequest.getAttribute("uid");
        reqActivityOrMatchDetail.setUid(userId);
        RespActivityOrMatchDetail respActivityOrMatchDetail = null;
        //根据场馆id，uid获取相关的活动信息
        RespLatesActivityInfo respLatesActivityInfo = null;
        try {
            respLatesActivityInfo = clubOpenService.latestActivityInfo(
                    reqActivityOrMatchDetail.getPlaceId()
                    , reqActivityOrMatchDetail.getUid()
                    , reqActivityOrMatchDetail.getCategoryId());
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }

        //根据场馆id，运动类别id，uid获取相关的比赛信息
        ResPlaceGameEventMsg resPlaceGameEventMsg = new ResPlaceGameEventMsg();
        try {
            resPlaceGameEventMsg = stadiumOpenService.getGameEventListByPlaceIdAndCategoryId(reqActivityOrMatchDetail.getUid(),
                    reqActivityOrMatchDetail.getCategoryId(), reqActivityOrMatchDetail.getPlaceId());
        } catch (Exception e) {
            logger.warn(e.getMessage());
            resPlaceGameEventMsg = new ResPlaceGameEventMsg();//之前运动场没有数据，也不会为null值，他们修改之后，会带入null值
            resPlaceGameEventMsg.setGameEventNum(0);
        }

        //比较活动和比赛的最新时间，选取最新的返回给客户端
        if (respLatesActivityInfo != null &&
                resPlaceGameEventMsg != null &&
                resPlaceGameEventMsg.getGameEventNum() > 0) {
            //如果活动时间大于比赛时间，返回活动详情
            if (respLatesActivityInfo.getActivityDate().getTime() > resPlaceGameEventMsg.getRecommendGameEvent().getStartTime()) {
                respActivityOrMatchDetail = setRespActivityOrMatchDetail(respLatesActivityInfo, null, reqActivityOrMatchDetail);
            } else {
                respActivityOrMatchDetail = setRespActivityOrMatchDetail(null, resPlaceGameEventMsg, reqActivityOrMatchDetail);
            }
            respActivityOrMatchDetail.setActivityCount(respLatesActivityInfo.getActivityCount()
                    + resPlaceGameEventMsg.getGameEventNum());

        } else if (null == respLatesActivityInfo && null != resPlaceGameEventMsg && resPlaceGameEventMsg.getGameEventNum() > 0) {
            //比赛系统有数据，返回比赛详情
            respActivityOrMatchDetail = setRespActivityOrMatchDetail(null, resPlaceGameEventMsg, reqActivityOrMatchDetail);

        } else if (null != respLatesActivityInfo && null != resPlaceGameEventMsg && resPlaceGameEventMsg.getGameEventNum() == 0) {
            //活动系统有数据，返回活动详情
            respActivityOrMatchDetail = setRespActivityOrMatchDetail(respLatesActivityInfo, null, reqActivityOrMatchDetail);
        } else if (null == respLatesActivityInfo && null != resPlaceGameEventMsg && resPlaceGameEventMsg.getGameEventNum() == 0) {
            respActivityOrMatchDetail = setRespActivityOrMatchDetail(null, null, reqActivityOrMatchDetail);
        } else {
            return APIResponse.returnFail("服务器异常！");
        }

        return APIResponse.returnSuccess(respActivityOrMatchDetail);
    }

    private RespActivityOrMatchDetail setRespActivityOrMatchDetail(RespLatesActivityInfo respLatesActivityInfo,
                                                                   ResPlaceGameEventMsg resPlaceGameEventMsg,
                                                                   ReqActivityOrMatchDetail reqActivityOrMatchDetail) {
        RespActivityOrMatchDetail respActivityOrMatchDetail = new RespActivityOrMatchDetail();
        if (respLatesActivityInfo != null && resPlaceGameEventMsg == null) {
            respActivityOrMatchDetail.setTitle(respLatesActivityInfo.getActivityTitle());
            respActivityOrMatchDetail.setActivityCount(respLatesActivityInfo.getActivityCount());
            respActivityOrMatchDetail.setId(respLatesActivityInfo.getActivityId());
            respActivityOrMatchDetail.setStartDate(respLatesActivityInfo.getActivityDate().getTime());
            respActivityOrMatchDetail.setIsJoin(respLatesActivityInfo.getAllReadySignUp());
            respActivityOrMatchDetail.setGroupid(respLatesActivityInfo.getGroupId());
            respActivityOrMatchDetail.setCurrentUid(respLatesActivityInfo.getUid());
            respActivityOrMatchDetail.setType(PlaceConstants.PLACE_ACTIVITY_TYPE);

        } else if (respLatesActivityInfo == null && resPlaceGameEventMsg != null) {
            ResUserGameEvent recommendGameEvent = resPlaceGameEventMsg.getRecommendGameEvent();
            respActivityOrMatchDetail.setTitle(recommendGameEvent.getName());
            respActivityOrMatchDetail.setActivityCount(resPlaceGameEventMsg.getGameEventNum());
            respActivityOrMatchDetail.setId(recommendGameEvent.getId());
            respActivityOrMatchDetail.setStartDate(recommendGameEvent.getStartTime());
            respActivityOrMatchDetail.setIsJoin(recommendGameEvent.getIsJoin());
            respActivityOrMatchDetail.setType(PlaceConstants.PLACE_MATCH_TYPE);
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqActivityOrMatchDetail.getPlaceId());
            if (tbBizPlace != null) {
                respActivityOrMatchDetail.setGroupid(tbBizPlace.getGroupId());//返回场馆群聊id
                respActivityOrMatchDetail.setCurrentUid(placeAdminUser);
            }
        } else if (respLatesActivityInfo == null && resPlaceGameEventMsg == null) {
            respActivityOrMatchDetail.setTitle("当前无比赛/活动");
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqActivityOrMatchDetail.getPlaceId());
            if (tbBizPlace != null) {
                respActivityOrMatchDetail.setGroupid(tbBizPlace.getGroupId());//返回场馆群聊id
                respActivityOrMatchDetail.setCurrentUid(placeAdminUser);
            }
            respActivityOrMatchDetail.setType(PlaceConstants.PLACE_NONE_TYPE);
            respActivityOrMatchDetail.setStartDate(System.currentTimeMillis());
            respActivityOrMatchDetail.setActivityCount(0);
            respActivityOrMatchDetail.setIsJoin(Constants.NO);
            respActivityOrMatchDetail.setId(0);
        }

        //获取群信息以及成员信息
        if (respActivityOrMatchDetail.getGroupid() != null) {
            ReqGetGroupInfo reqGetGroupInfo = new ReqGetGroupInfo();
            reqGetGroupInfo.setGroupid(respActivityOrMatchDetail.getGroupid());
            reqGetGroupInfo.setCurrentUid(respActivityOrMatchDetail.getCurrentUid());
            Membersparam membersparam = new Membersparam();
            membersparam.setPagenum(0);
            membersparam.setOffset(4);
            membersparam.setVer(0);
            reqGetGroupInfo.setMembersparam(membersparam);
            String json = JSON.toJSONString(reqGetGroupInfo);

            String result = null;
            try {
                result = HttpClientUtils.postJson(cAddress + "/IM/getGroupInfo.api", json);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String data = jsonObject.getString("data");
                if (!StringUtil.isBlankOrNull(data)) {
                    RespGroupInfo respGroupInfo = JSON.parseObject(data, RespGroupInfo.class);
                    respGroupInfo.setGroupid(respActivityOrMatchDetail.getGroupid());
                    respActivityOrMatchDetail.setRespGroupInfo(respGroupInfo);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return respActivityOrMatchDetail;
    }

    private void setPlaceInfoBySalePlan(RespPlaceUnitSalePlanDetail placeUnitSalePlanDetail,
                                        RespBizPlaceBaseInfo respBizPlaceBaseInfo, ReqPlaceSalePlan reqPlaceSalePlan,
                                        String earlyStartTime, String lateEndTime, Set<Integer> orderBundleNoSet) {
        placeUnitSalePlanDetail.setName(respBizPlaceBaseInfo.getName());
        placeUnitSalePlanDetail.setPhone(respBizPlaceBaseInfo.getPhone());
        placeUnitSalePlanDetail.setAddress(respBizPlaceBaseInfo.getAddress());
        placeUnitSalePlanDetail.setCommentCount(respBizPlaceBaseInfo.getCommentCount());
        placeUnitSalePlanDetail.setPlaceScore(respBizPlaceBaseInfo.getPlaceScore());
        placeUnitSalePlanDetail.setCityObj(respBizPlaceBaseInfo.getCityObj());
        placeUnitSalePlanDetail.setDistrictObj(respBizPlaceBaseInfo.getDistrictObj());
        placeUnitSalePlanDetail.setIsShelves(respBizPlaceBaseInfo.getIsShelves());

        List<RespCategory> respCategories = new ArrayList<>();
        List<RespCategory> respBizPlaceBaseInfoCategories = respBizPlaceBaseInfo.getCategorys();
        if (CollectionUtils.isNotEmpty(respBizPlaceBaseInfoCategories)) {
            for (RespCategory respCategory : respBizPlaceBaseInfoCategories) {
                if (respCategory.getId().intValue() == reqPlaceSalePlan.getCategoryId().intValue()) {
                    respCategories.add(0, respCategory);
                } else {
                    respCategories.add(respCategory);
                }
            }
            placeUnitSalePlanDetail.setCategorys(respCategories);
        }

        //设置场馆是否包含门票
        Integer isIncludeTicket = 0;
        TbPlaceTicketSalePlanExample tbPlaceTicketSalePlanExample = new TbPlaceTicketSalePlanExample();
        TbPlaceTicketSalePlanExample.Criteria tbPlaceTicketSalePlanCriteria = tbPlaceTicketSalePlanExample.createCriteria();
        tbPlaceTicketSalePlanCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
        tbPlaceTicketSalePlanCriteria.andCategoryIdEqualTo(reqPlaceSalePlan.getCategoryId());
        tbPlaceTicketSalePlanCriteria.andStatusEqualTo(PlaceConstants.YES);
        tbPlaceTicketSalePlanExample.setPage(new Page(0, 1));
        List<TbPlaceTicketSalePlan> tbPlaceTicketSalePlans = tbPlaceTicketSalePlanMapper.selectByExample(tbPlaceTicketSalePlanExample);
        if (CollectionUtils.isNotEmpty(tbPlaceTicketSalePlans)) {
            if (tbPlaceTicketSalePlans.size() > 0) {
                isIncludeTicket = 1;
            }
        }
        placeUnitSalePlanDetail.setIsIncludeTicket(isIncludeTicket);

        TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
        TbBizPlaceRuleExample.Criteria tbBizPlaceRuleCriteria = tbBizPlaceRuleExample.createCriteria();
        tbBizPlaceRuleCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
        List<TbBizPlaceRule> tbBizPlaceRuleList = tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
        if (CollectionUtils.isEmpty(tbBizPlaceRuleList)) {
            // placeUnitSalePlanDetail.setIsContainOtherDate(PlaceConstants.CONTAIN_OTHER_DATE);//默认不显示其他日期
            placeUnitSalePlanDetail.setIsContainOtherDate(PlaceConstants.YES);//默认显示其它日期
            placeUnitSalePlanDetail.setSyncSalePlanCycle(PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD);
            placeUnitSalePlanDetail.setTips("温馨提示：本场馆仅支持提前" + PlaceConstants.PLACE_UNSUBSCRIBE_TIME + "小时退订！");
            placeUnitSalePlanDetail.setOnceOrderMaxTime(PlaceConstants.PLACE_ONCE_ORDER_MAX_TIME);
            logger.info("下单信息验证规则从默认配置中获取，placeId={}", reqPlaceSalePlan.getPlaceId());
        } else {
            placeUnitSalePlanDetail.setIsContainOtherDate(tbBizPlaceRuleList.get(0).getIsContainOtherDate());
            placeUnitSalePlanDetail.setSyncSalePlanCycle(tbBizPlaceRuleList.get(0).getSyncSalePlanCycle());
            placeUnitSalePlanDetail.setOnceOrderMaxTime(tbBizPlaceRuleList.get(0).getOnceOrderMaxTime());//用户一次可预定最大的时段总数
            if (tbBizPlaceRuleList.get(0).getUnsubscribeTime() > 0) {
                placeUnitSalePlanDetail.setTips("温馨提示：本场馆仅支持提前" + tbBizPlaceRuleList.get(0).getUnsubscribeTime() + "小时退订！");
            } else {
                placeUnitSalePlanDetail.setTips("温馨提示：本场馆不支持退订！");
            }

        }

        List<AvailableDate> availableDateList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {//TODO 天数从数据库查
            AvailableDate availableDate = new AvailableDate();
            long auctionTime = 0;
            if (reqPlaceSalePlan.getIsAuction() != null && reqPlaceSalePlan.getIsAuction().equals(1)) {
                auctionTime = 5 * 86400000L;
            }
            long temp = i * 86400000L + auctionTime;
            long time = System.currentTimeMillis() + temp;
            String date = DateUtils.transferLongToDateString(time);
            availableDate.setDate(date);
            availableDate.setWeek(DateUtils.dayForWeek(date));
            availableDateList.add(availableDate);
        }
        placeUnitSalePlanDetail.setAvailableDateList(availableDateList);


        Byte isNormalDateInterval = PlaceConstants.NO;
        if (placeUnitSalePlanDetail.getSyncSalePlanCycle() > 0) {
            long startInterval = 7 * 86400000L;
            long endInterval = (placeUnitSalePlanDetail.getSyncSalePlanCycle() * 7 - 1) * 86400000L;
            if (placeUnitSalePlanDetail.getSyncSalePlanCycle() == 1) {
                startInterval = 0;
                endInterval = 0;
            }
            long starttime = System.currentTimeMillis() + startInterval;
            long endtime = System.currentTimeMillis() + endInterval;
            if (reqPlaceSalePlan.getStartDate() <= endtime && reqPlaceSalePlan.getEndDate() <= endtime) {
                placeUnitSalePlanDetail.setExtendStartDate(starttime);
                placeUnitSalePlanDetail.setExtendEndDate(endtime);
                isNormalDateInterval = PlaceConstants.YES;
            }
        }

        //判断是否为会员
        if (reqPlaceSalePlan.getUid() > 0 && placeMemberService.isPlaceMember(reqPlaceSalePlan.getUid(),
                reqPlaceSalePlan.getPlaceId(), reqPlaceSalePlan.getCategoryId(), 0)) {
            placeUnitSalePlanDetail.setIsMember(1);
            placeUnitSalePlanDetail.setMemberTips("您是本场馆尊贵会员，享受会员价优惠订场！");
        } else {
            placeUnitSalePlanDetail.setIsMember(0);
            placeUnitSalePlanDetail.setMemberTips("会员可享受更多折扣哦！点击");
        }


        //获取场馆附属信息
        TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
        TbBizPlaceAttachExample.Criteria tbBizPlaceAttachCriteria = example.createCriteria();
        tbBizPlaceAttachCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
        List<TbBizPlaceAttach> result = tbBizPlaceAttachMapper.selectByExample(example);

        Map map = this.placeUnitSalePlanMapper.getPlaceUnitTime(reqPlaceSalePlan.getPlaceId(), reqPlaceSalePlan.getCategoryId());
        placeUnitSalePlanDetail.setStartTime(MapUtils.getString(map, "startTime"));
        placeUnitSalePlanDetail.setEndTime(MapUtils.getString(map, "endTime"));

        //placeUnitSalePlanDetail.setStartTime("08:00");
        //placeUnitSalePlanDetail.setEndTime("22:00");
        placeUnitSalePlanDetail.setIsContainVip(PlaceConstants.NO);


        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqPlaceSalePlan.getPlaceId());
        if(null != tbBizPlace){
            placeUnitSalePlanDetail.setLat(tbBizPlace.getLat()!= null ? tbBizPlace.getLat():null);
            placeUnitSalePlanDetail.setLng(tbBizPlace.getLng()!= null ? tbBizPlace.getLng():null);
        }


        if (CollectionUtils.isNotEmpty(result)) {
            TbBizPlaceAttach tbBizPlaceAttach = result.get(0);
           /* if (tbBizPlaceAttach.getBusinessHourStart().compareTo(tbBizPlaceAttach.getHolidayBusinessHourStart()) >= 0) {
                placeUnitSalePlanDetail.setStartTime(tbBizPlaceAttach.getHolidayBusinessHourStart());
            } else {
                placeUnitSalePlanDetail.setStartTime(tbBizPlaceAttach.getBusinessHourStart());
            }

            if (tbBizPlaceAttach.getBusinessHourEnd().compareTo(tbBizPlaceAttach.getHolidayBusinessHourEnd()) >= 0) {
                placeUnitSalePlanDetail.setEndTime(tbBizPlaceAttach.getBusinessHourEnd());
            } else {
                placeUnitSalePlanDetail.setEndTime(tbBizPlaceAttach.getHolidayBusinessHourEnd());
            }*/

            //placeUnitSalePlanDetail.setStartTime(tbBizPlaceAttach.getBusinessHourStart());
            //placeUnitSalePlanDetail.setEndTime(tbBizPlaceAttach.getBusinessHourEnd());
            placeUnitSalePlanDetail.setOffsetTime(1);

            if (placeMemberService.isPlaceContainMemberCard(reqPlaceSalePlan.getPlaceId())
                    && tbBizPlaceAttach.getIsVip() == 1) {
                // 场馆支持会员卡
                placeUnitSalePlanDetail.setIsContainVip(tbBizPlaceAttach.getIsVip());
            } else {
                placeUnitSalePlanDetail.setIsContainVip(PlaceConstants.NO);
            }
        }


      /*  String startTime = placeUnitSalePlanDetail.getStartTime();
        if (earlyStartTime != null && startTime.compareTo(earlyStartTime) >= 0) {
            startTime = earlyStartTime;
            placeUnitSalePlanDetail.setStartTime(startTime);
        }

        String endTime = placeUnitSalePlanDetail.getEndTime();
        if (lateEndTime != null && endTime.compareTo(lateEndTime) <= 0) {
            endTime = lateEndTime;
            placeUnitSalePlanDetail.setEndTime(endTime);
        }*/

        //根据请求参数判断是否需要补全销售计划列表
       /* List<String> list = getIntervalTimeList(startTime,
                endTime, placeUnitSalePlanDetail.getOffsetTime() * 60);
        placeUnitSalePlanDetail.setTimeList(list);*/

        /**注释**/
       /* List<String> list = PlaceOrderUtil.getIntervalTimeList(placeUnitSalePlanDetail.getStartTime(),
                placeUnitSalePlanDetail.getEndTime(), placeUnitSalePlanDetail.getOffsetTime() * 60);
        placeUnitSalePlanDetail.setTimeList(list);
     */
        /**
         * 添加此段
         */
        TbBizPlaceCategory placeCategory = placeBaseService.getPlaceCategory(reqPlaceSalePlan.getPlaceId(),
                Integer.valueOf(reqPlaceSalePlan.getCategoryId()));
        int intervalTime = PlaceUtil.getTimeInterval(placeCategory.getMinSaleTimeUnit());

        List<String> list = PlaceOrderUtil.getIntervalTimeList(placeUnitSalePlanDetail.getStartTime(),
                placeUnitSalePlanDetail.getEndTime(), intervalTime);
        logger.info("------------->List：{}",JSON.toJSONString(list));
        placeUnitSalePlanDetail.setTimeList(list);

        if (PlaceConstants.YES.equals(reqPlaceSalePlan.getIsAutoCompleteSalePlan())
                && PlaceConstants.YES.equals(isNormalDateInterval)
                && CollectionUtils.isNotEmpty(placeUnitSalePlanDetail.getPlaceUnitInfoVoList())) {
            List<RespPlaceUnitSalePlanByDay> placeUnitInfoVoListTemp = placeUnitSalePlanDetail.getPlaceUnitInfoVoList();
            for (RespPlaceUnitSalePlanByDay respPlaceUnitSalePlanByDay : placeUnitInfoVoListTemp) {
                List<RespPlaceUnitInfoVo> placeUnitList = respPlaceUnitSalePlanByDay.getPlaceUnitList();
                for (RespPlaceUnitInfoVo respPlaceUnitInfoVo : placeUnitList) {
                    List<RespPlaceUnitSalePlanVo> placeUnitSalePlanList = respPlaceUnitInfoVo.getPlaceUnitSalePlanList();
                    List<RespPlaceUnitSalePlanVo> placeUnitSalePlanListTemp =
                            PlaceOrderUtil.getAllRespPlaceUnitSalePlanVoList(list, placeUnitSalePlanList);
                    //遍历销售计划列表，判断捆绑id是否存在于orderBundleNoSet集合中，如果存在置为已售状态。
                    for (RespPlaceUnitSalePlanVo respPlaceUnitSalePlanVo : placeUnitSalePlanListTemp) {
                        RespPlaceUnitSalePlan respPlaceUnitSalePlan = respPlaceUnitSalePlanVo.getRespPlaceUnitSalePlan();
                        if (null != respPlaceUnitSalePlan.getPlaceUnitId()){
                            if (orderBundleNoSet.contains(respPlaceUnitSalePlan.getBundleNo()+respPlaceUnitSalePlan.getPlaceUnitId())) {
                                respPlaceUnitSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
                            }
                        }
                    }
                    respPlaceUnitInfoVo.setPlaceUnitSalePlanList(placeUnitSalePlanListTemp);
                }
            }
        } else if (PlaceConstants.YES.equals(reqPlaceSalePlan.getIsAutoCompleteSalePlan())
                && PlaceConstants.YES.equals(isNormalDateInterval)
                && CollectionUtils.isEmpty(placeUnitSalePlanDetail.getPlaceUnitInfoVoList())) {
            List<RespPlaceUnitSalePlanByDay> placeUnitInfoVoListTemp = new ArrayList<>();
            RespPlaceUnitSalePlanByDay placeUnitSalePlanByDay = new RespPlaceUnitSalePlanByDay();
            List<RespPlaceUnitInfoVo> placeUnitListTemp = new ArrayList<>();

            TbBizPlaceUnitExample tbBizPlaceUnitExample = new TbBizPlaceUnitExample();
            TbBizPlaceUnitExample.Criteria tbBizPlaceUnitCriteria = tbBizPlaceUnitExample.createCriteria();
            tbBizPlaceUnitCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
            tbBizPlaceUnitCriteria.andCategoryIdEqualTo(reqPlaceSalePlan.getCategoryId().byteValue());
            tbBizPlaceUnitCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            tbBizPlaceUnitExample.setOrderByClause("name");//按照场地名称排序，+0将MySQL字符串字段按数值排序

            List<TbBizPlaceUnit> tbBizPlaceUnits = placeUnitMapper.selectByExample(tbBizPlaceUnitExample);

            for (TbBizPlaceUnit tbBizPlaceUnit : tbBizPlaceUnits) {
                RespPlaceUnitInfo respPlaceUnitInfoTemp = new RespPlaceUnitInfo();
                respPlaceUnitInfoTemp.setId(tbBizPlaceUnit.getId());
                respPlaceUnitInfoTemp.setName(tbBizPlaceUnit.getName());
                RespPlaceUnitInfoVo respPlaceUnitInfoVoTemp = new RespPlaceUnitInfoVo();
                respPlaceUnitInfoVoTemp.setRespPlaceUnitInfo(respPlaceUnitInfoTemp);//场地详情

                List<RespPlaceUnitSalePlanVo> respPlaceUnitSalePlanVoList = new ArrayList<>();
                for (int i = 0; i < list.size() - 1; i++) {
                    RespPlaceUnitSalePlan respPlaceUnitSalePlan = new RespPlaceUnitSalePlan();
                    respPlaceUnitSalePlan.setStartTime(list.get(i));
                    respPlaceUnitSalePlan.setEndTime(list.get(i + 1));
                    respPlaceUnitSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
                    RespPlaceUnitSalePlanVo respPlaceUnitSalePlanVoTemp = new RespPlaceUnitSalePlanVo();
                    respPlaceUnitSalePlanVoTemp.setRespPlaceUnitSalePlan(respPlaceUnitSalePlan);
                    respPlaceUnitSalePlanVoList.add(respPlaceUnitSalePlanVoTemp);
                }
                respPlaceUnitInfoVoTemp.setPlaceUnitSalePlanList(respPlaceUnitSalePlanVoList);

                placeUnitListTemp.add(respPlaceUnitInfoVoTemp);
            }
            placeUnitSalePlanByDay.setPlaceUnitList(placeUnitListTemp);
            placeUnitSalePlanByDay.setDate(availableDateList.get(0).getDate());
            placeUnitSalePlanByDay.setWeek(availableDateList.get(0).getWeek());
            placeUnitInfoVoListTemp.add(placeUnitSalePlanByDay);
            placeUnitSalePlanDetail.setPlaceUnitInfoVoList(placeUnitInfoVoListTemp);
        }

    }

    @Override
    public PageObj<List<RespActivityOrMatchList>> activityOrMatchList(ReqActivityOrMatchList reqActivityOrMatchList) {
        PageObj<List<RespActivityOrMatchList>> result = null;
        ReqLastGameEvent reqLastGameEvent = new ReqLastGameEvent();
        reqLastGameEvent.setCategoryId(reqActivityOrMatchList.getCategoryId());
        reqLastGameEvent.setPlaceId(reqActivityOrMatchList.getPlaceId());
        reqLastGameEvent.setPageCount(reqActivityOrMatchList.getPageCount());
        reqLastGameEvent.setPageNum(reqActivityOrMatchList.getPageNum());
        PageObj<List<GameEventSummary>> gameEventSummaryPageObj = null;
        List<RespActivityOrMatchList> respActivityOrMatchListList = new ArrayList<>();
        try {
            gameEventSummaryPageObj = stadiumOpenService.getLastGameEventsByPlaceIdAndCategoryId(reqLastGameEvent);
            if (gameEventSummaryPageObj != null) {
                List<GameEventSummary> gameEventSummaryList = gameEventSummaryPageObj.getItems();
                if (CollectionUtils.isNotEmpty(gameEventSummaryList)) {
                    for (GameEventSummary gameEventSummary : gameEventSummaryList) {
                        RespActivityOrMatchList respActivityOrMatchList = new RespActivityOrMatchList();
                        BeanUtils.copyProperties(gameEventSummary, respActivityOrMatchList);
                        respActivityOrMatchList.setType(PlaceConstants.PLACE_MATCH_TYPE);
                        respActivityOrMatchListList.add(respActivityOrMatchList);
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        PageObj<List<RespClubActivity>> clubActivityPageObj = null;
        try {
            clubActivityPageObj = clubOpenService.latestActivityList4Place(reqActivityOrMatchList.getPlaceId(),
                    reqActivityOrMatchList.getPageNum(), reqActivityOrMatchList.getPageCount());
            if (clubActivityPageObj != null) {
                List<RespClubActivity> respClubActivityList = clubActivityPageObj.getItems();
                if (CollectionUtils.isNotEmpty(respClubActivityList)) {
                    for (RespClubActivity respClubActivity : respClubActivityList) {
                        RespActivityOrMatchList respActivityOrMatchList = new RespActivityOrMatchList();
                        respActivityOrMatchList.setId(respClubActivity.getActivityId());
                        respActivityOrMatchList.setName(respClubActivity.getName());
                        respActivityOrMatchList.setStartTime(respClubActivity.getStartTime().getTime());
                        respActivityOrMatchList.setEndTime(respClubActivity.getEndTime().getTime());
                        respActivityOrMatchList.setImageUrl(respClubActivity.getRespActivityPoster().getUrl());
                        respActivityOrMatchList.setPrice(respClubActivity.getPrice());
                        respActivityOrMatchList.setActivityType(respClubActivity.getActivityType());
                        respActivityOrMatchList.setType(PlaceConstants.PLACE_ACTIVITY_TYPE);
                        respActivityOrMatchListList.add(respActivityOrMatchList);
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gameEventSummaryPageObj != null && clubActivityPageObj != null) {
            result = PageObj.create(gameEventSummaryPageObj.getTotal() + clubActivityPageObj.getTotal(),
                    gameEventSummaryPageObj.getPageNum(), gameEventSummaryPageObj.getSize(), respActivityOrMatchListList);
        } else if (gameEventSummaryPageObj != null && clubActivityPageObj == null) {
            result = PageObj.create(gameEventSummaryPageObj.getTotal(), gameEventSummaryPageObj.getPageNum(),
                    gameEventSummaryPageObj.getSize(), respActivityOrMatchListList);
        } else if (gameEventSummaryPageObj == null && clubActivityPageObj != null) {
            result = PageObj.create(clubActivityPageObj.getTotal() + clubActivityPageObj.getTotal(),
                    clubActivityPageObj.getPageNum(), clubActivityPageObj.getSize(), respActivityOrMatchListList);
        } else {
            result = PageObj.create(0, 0, 0, null);
        }
        return result;
    }

    @Override
    public APIResponse<RespShareUrl> shareUrl(ReqShareUrl reqShareUrl) {
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer uid = (Integer) httpServletRequest.getAttribute("uid");
        APIResponse<RespUserInfoBase> result = null;
        String shareUrl = reqShareUrl.getUrl();
        String httpresult = null;
        if (shareUrl == null) {
            try {
                if (uid == 0 || uid == null) {
                    return APIResponse.returnFail(ApiResponseEnum.NEED_USER_LOGIN);
                }
                String userToken = (String) placeRedisTemplate.get(PlaceConstants.USER_SHARE_PREFIX + uid);
                if (userToken == null) {
                    userToken = UUIDUtils.getUUID();
                    placeRedisTemplate.set(PlaceConstants.USER_SHARE_PREFIX + uid, userToken, Constants.SHARE_TOKEN_EXPIRED_TIME);
                    placeRedisTemplate.set(userToken, uid, Constants.SHARE_TOKEN_EXPIRED_TIME);
                }
                result = userServiceFacade.queryUserInfo(uid);
                if (result.isRet()) {
                    String nickName = result.getData().getNickName();
                    String icon = result.getData().getIcon();
                    shareUrl = placeShareUrl + "?token=" + userToken + "&nickName=" + nickName + "&icon=" + icon;
                }
            } catch (Exception e) {
                logger.warn(e.getMessage());
                return APIResponse.returnFail("获取用户信息异常。");
            }
        }

        if (reqShareUrl.getType().equals(0) || reqShareUrl.getType().equals(2)) {
            try {
                httpresult = ShortUrlUtils.getShortUrl(shareUrl);
                if (httpresult != null) {
                    List<RespShareUrl> respShareUrls = JSON.parseArray(httpresult, RespShareUrl.class);
                    if (reqShareUrl.getType().equals(2)) {
                        respShareUrls.get(0).setUrl_long(null);
                    }
                    respShareUrls.get(0).setType(reqShareUrl.getType());
                    String urlShort = respShareUrls.get(0).getUrl_short();
                    if (StringUtils.isEmpty(urlShort)){
                        respShareUrls.get(0).setUrl_short("");
                    }
                    return APIResponse.returnSuccess(respShareUrls.get(0));
                }
            } catch (Exception e) {
                logger.warn(e.getMessage());
            }
        }

        RespShareUrl respShareUrl = new RespShareUrl();
        respShareUrl.setType(1);
        respShareUrl.setUrl_short("");
        respShareUrl.setUrl_long(shareUrl);

        return APIResponse.returnSuccess(respShareUrl);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBillingForMember(ReqBillingInfo reqBillingInfo) throws Exception {
        //查询场馆单元销售计划价格
        List<UnitSaleInfo> unitSaleInfos = reqBillingInfo.getUnitSaleInfos();
        if (CollectionUtils.isNotEmpty(unitSaleInfos)) {
            // TODO: 16/6/16 客户端提供修改价格,暂时没用到
        }
        String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
        /*TbBizPlaceUnitSalePlanExample unitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        unitSalePlanExample.createCriteria().andPlaceUnitIdIn(unitids);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(unitSalePlanExample);*/
        List<UnitSalePlan> list = new ArrayList<>();
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();

        for (String unitid : unitids) {
            UnitSalePlan unit = new UnitSalePlan();
            unit.setSaleId(unitid);
            list.add(unit);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(list);

        if (reqPlaceOrderListVo.getPlaceId() == null) {
            reqPlaceOrderListVo.setPlaceId(reqBillingInfo.getPlaceId());
        }

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans =
                placeOrderService.lockTbBizPlaceUnitSalePlanEx(reqPlaceOrderListVo, PlaceConstants.PLACE_LOCk_STATUS);

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            logger.error("没有对应的销售计划:reqBillingInfo:{}", reqBillingInfo.toString());
            return APIResponse.returnFail("没有对应的销售计划");
        }
        //判断是否可销售
        TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = baseService.getNotSellPlan(tbBizPlaceUnitSalePlans);
        if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan)) {
            return APIResponse.returnFail(tbBizPlaceUnitSalePlan.getSaleId() + "不可预订");
        }

        //插入数据库
        logger.debug("===================开始插入数据库:ReqBillingInfo:{}", JSON.toJSONString(reqBillingInfo));

        try {
            return placeOrderService.saveBillingForMember(reqBillingInfo);
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBillingForMemberPlus(ReqBillingInfo reqBillingInfo) throws Exception {
        if (StringUtils.isEmpty(reqBillingInfo.getReceivedAmount())){
            return APIResponse.returnFail("实收金额不能为空！");
        }

        if (StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())){
            return APIResponse.returnFail("saleId参数错误");
        }

        String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");

        List<UnitSalePlan> list = new ArrayList<>();
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();

        for (String unitid : unitids) {
            UnitSalePlan unit = new UnitSalePlan();
            unit.setSaleId(unitid);
            list.add(unit);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(list);
        if (reqBillingInfo.getPlaceId() != null) {
            reqPlaceOrderListVo.setPlaceId(reqBillingInfo.getPlaceId());
        }

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = placeUnitSalePlanMapper.selectByPrimaryKeyList(reqPlaceOrderListVo);
        //判断是否可销售
        TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = baseService.getNotSellPlan(tbBizPlaceUnitSalePlanList);
        if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan)) {
            return APIResponse.returnFail(tbBizPlaceUnitSalePlan.getSaleId() + "不可预订");
        }

        try {
            placeOrderService.lockTbBizPlaceUnitSalePlanExPlus(reqPlaceOrderListVo);
        } catch (Exception e){
            throw e;
        }

        APIResponse apiResponse = null;
        try {
            apiResponse = placeOrderService.saveBillingForMemberPlus(reqBillingInfo);
            if (!apiResponse.isRet()){
                throw new BizException(apiResponse.getErrmsg());
            }
        } catch (Exception e) {
            throw e;
        }
        return apiResponse;
    }

    /**
     * 商家端会员预订
     *
     * @param reqBillingInfo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBookForMember(ReqBillingInfo reqBillingInfo) throws Exception {
        //查询场馆单元销售计划价格
        List<UnitSaleInfo> unitSaleInfos = reqBillingInfo.getUnitSaleInfos();
        if (CollectionUtils.isNotEmpty(unitSaleInfos)) {
            // TODO: 16/6/16 客户端提供修改价格,暂时没用到
        }
        String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
        /*TbBizPlaceUnitSalePlanExample unitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        unitSalePlanExample.createCriteria().andPlaceUnitIdIn(unitids);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(unitSalePlanExample);*/
        List<UnitSalePlan> list = new ArrayList<>();
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();

        for (String unitid : unitids) {
            UnitSalePlan unit = new UnitSalePlan();
            unit.setSaleId(unitid);
            list.add(unit);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(list);

        if (reqPlaceOrderListVo.getPlaceId() == null) {
            reqPlaceOrderListVo.setPlaceId(reqBillingInfo.getPlaceId());
        }
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans =
                placeOrderService.lockTbBizPlaceUnitSalePlanEx(reqPlaceOrderListVo, PlaceConstants.PLACE_LOCk_STATUS);

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            logger.error("没有对应的销售计划:reqBillingInfo:{}", reqBillingInfo.toString());
            return APIResponse.returnFail("没有对应的销售计划");
        }
        //判断是否可销售
        TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = baseService.getNotSellPlan(tbBizPlaceUnitSalePlans);
        if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan)) {
            return APIResponse.returnFail(tbBizPlaceUnitSalePlan.getSaleId() + "不可预订");
        }
        //插入数据库
        logger.debug("===================开始插入数据库:ReqBillingInfo:{}", JSON.toJSONString(reqBillingInfo));
        try {
            if (placeOrderService.saveBookForMember(reqBillingInfo)) {
                return APIResponse.returnSuccess();
            }
        } catch (Exception e) {
            throw e;
        }
        return APIResponse.returnFail("会员预订失败");
    }

    /**
     * 商家端会员预订
     *
     * @param reqBillingInfo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBookForMemberPlus(ReqBillingInfo reqBillingInfo) throws Exception {
        if (StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())){
            return APIResponse.returnFail("saleId参数错误");
        }

        String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");

        List<UnitSalePlan> list = new ArrayList<>();
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();

        for (String unitid : unitids) {
            UnitSalePlan unit = new UnitSalePlan();
            unit.setSaleId(unitid);
            list.add(unit);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(list);
        if (reqBillingInfo.getPlaceId() != null) {
            reqPlaceOrderListVo.setPlaceId(reqBillingInfo.getPlaceId());
        }

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = placeUnitSalePlanMapper.selectByPrimaryKeyList(reqPlaceOrderListVo);
        //判断是否可销售
        TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = baseService.getNotSellPlan(tbBizPlaceUnitSalePlanList);
        if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan)) {
            return APIResponse.returnFail(tbBizPlaceUnitSalePlan.getSaleId() + "不可预订");
        }

        try {
            placeOrderService.lockTbBizPlaceUnitSalePlanExPlus(reqPlaceOrderListVo);
        } catch (Exception e){
            throw e;
        }

        APIResponse apiResponse = null;
        try {
            apiResponse = placeOrderService.saveBookForMemberPlus(reqBillingInfo);
            if (!apiResponse.isRet()){
                throw new BizException(apiResponse.getErrmsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("会员预订生成订单失败");
        }
        return apiResponse;
    }

    /**
     * 商家端会员包场
     *
     * @param reqBillingInfo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBookAllForMember(ReqBillingInfo reqBillingInfo) throws Exception {
        // 1.查询客户端返回时间段 周几 `place_id` `place_unit_id`  根据销售模板计算销售计划的总数
        // 2.判断有的就更新  没有就插入
        if (!StringUtils.isEmpty(reqBillingInfo.getWeeks())) {
            String[] ids1 = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getWeeks(), ",");
            List<String> list = Arrays.asList(ids1);
            List<Integer> weekList = new ArrayList<>();
            for (String weekstr : list) {
                weekList.add(Integer.parseInt(weekstr));
            }
            reqBillingInfo.setWeek(weekList);
        }

        //=======校验是否有存在不可售的销售计划（防止超卖情况） 开始=========
        if (CollectionUtils.isEmpty(reqBillingInfo.getUnitSaleInfos())){
            return APIResponse.returnFail("场地信息必传");
        }
        PlaceBookAllCheckVo placeBookAllCheckVo = new PlaceBookAllCheckVo();
        placeBookAllCheckVo.setPlaceId(reqBillingInfo.getPlaceId());
        placeBookAllCheckVo.setCategoryId(reqBillingInfo.getCategoryId());
        placeBookAllCheckVo.setEndDate(DateUtils.transferLongToDate(reqBillingInfo.getEndDate()));
        placeBookAllCheckVo.setStartDate(DateUtils.transferLongToDate(reqBillingInfo.getStartDate()));
        placeBookAllCheckVo.setTimeTypeList(reqBillingInfo.getWeek());
        List<UnitSaleInfo> unitSaleInfoList = new ArrayList<>();
        for (UnitSaleInfo unitSaleInfo : reqBillingInfo.getUnitSaleInfos()){
            unitSaleInfoList.add(unitSaleInfo);
            placeBookAllCheckVo.setPlaceUnitSaleInfoList(unitSaleInfoList);
        }
        List<String> tbSaleIds = placeBlockBookingOrderMapper.checkBookAllOrder(placeBookAllCheckVo);
        List<String> reqSaleIdList = null;
        if (!StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())) {
            String[] saleIds = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
            reqSaleIdList = Arrays.asList(saleIds);
        }
        if (CollectionUtils.isEmpty(reqSaleIdList)){
            return APIResponse.returnFail("saleIds必传");
        }
        tbSaleIds.retainAll(reqSaleIdList);//取交集
        logger.error(tbSaleIds.toString()+"场地不可售卖");
        if (CollectionUtils.isNotEmpty(tbSaleIds)){
            return APIResponse.returnFail(tbSaleIds.toString()+"场地不可售卖");
        }
        //=======校验是否有存在不可售的销售计划（防止超卖情况） 结束=========

        if (!StringUtils.isEmpty(reqBillingInfo.getUnitIds())) {
            String[] unitIds = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getUnitIds(), ",");
            List<String> unitList = Arrays.asList(unitIds);
            List<Integer> unitIdList = new ArrayList<>();
            for (String unitstr : unitList) {
                unitIdList.add(Integer.parseInt(unitstr));
            }
            reqBillingInfo.setUnitId(unitIdList);
        }
        List<TbBizPlaceUnitSalePlan> resultList = new ArrayList<>();
        logger.debug("====================开始增加销售计划");
        //包场增加销售计划
        Date startDate = new Date(reqBillingInfo.getStartDate());
        Date endDate = new Date(reqBillingInfo.getEndDate());

        //获取日期内符合星期的销售列表
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = getTbBizPlaceUnitSalePlanByPlaceBoookAll(reqBillingInfo,
                startDate, endDate);
        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return APIResponse.returnFail("选择的星期不在日期范围内");
        }

        //获取销售计划模板
        List<String> types = new ArrayList<>();
        for (Integer type : reqBillingInfo.getWeek()) {
            types.add(type + "");
        }
        TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
        TbBizPlaceUnitSalePlanMainExample.Criteria mainCriteria = tbBizPlaceUnitSalePlanMainExample.createCriteria();
        mainCriteria.andIsEffectiveEqualTo(Constants.IS_ENABLE_TRUE).andPlaceIdEqualTo(reqBillingInfo.getPlaceId())
                .andPlaceUnitIdIn(reqBillingInfo.getUnitId())
                .andCategoryIdEqualTo(reqBillingInfo.getCategoryId()).andTimeTypeIn(types);
        List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMains = tbBizPlaceUnitSalePlanMainMapper
                .selectByExample(tbBizPlaceUnitSalePlanMainExample);
        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMains)) {
            logger.error("==========================没有销售计划模板 ReqPlaceSalePlan:{}",
                    JSON.toJSONString(reqBillingInfo));
            RespBizCodeInfo respBizCodeInfo = new RespBizCodeInfo();
            respBizCodeInfo.setSuccess(false);
            respBizCodeInfo.setGetCode(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getCode());
            respBizCodeInfo.setGetId(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getId());
            respBizCodeInfo.setGetLabel(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getLabel());
            return APIResponse.returnSuccess(respBizCodeInfo);
        }

        // 查询该场馆的所有的组合场信息
        List<PlaceCombinedUnitVo> allCUs = placeUCService.getCombinedUnits(reqBillingInfo.getPlaceId(), reqBillingInfo.getCategoryId(), null);
        Map<Integer, PlaceCombinedUnitVo> CUMap = new HashMap();
        if (allCUs != null && allCUs.size() > 0) {
            for (PlaceCombinedUnitVo cu : allCUs) {
                if (!CUMap.containsKey(cu.getId())) {
                    CUMap.put(cu.getId(), cu);
                }
            }
        }

        List tbMainList = new ArrayList();
        for (TbBizPlaceUnitSalePlan tbUnitSalePlan1 : tbBizPlaceUnitSalePlans) {
            for (TbBizPlaceUnitSalePlanMain tbMain : tbBizPlaceUnitSalePlanMains) {
                //去除销售计划模板中没有的数据
                if (tbUnitSalePlan1.getPlaceUnitId().intValue() == tbMain.getPlaceUnitId().intValue() &&
                        tbUnitSalePlan1.getTimeType().equals(tbMain.getTimeType())
                        && (tbUnitSalePlan1.getStartTime().equals(tbMain.getStartTime())
                        && tbUnitSalePlan1.getEndTime().equals(tbMain.getEndTime()))) {
                    TbBizPlaceUnitSalePlan tbUnitSalePlan = new TbBizPlaceUnitSalePlan();
                    BeanUtils.copyProperties(tbUnitSalePlan1, tbUnitSalePlan);
                    tbUnitSalePlan.setPlaceId(tbMain.getPlaceId());
                    tbUnitSalePlan.setPlaceUnitId(tbMain.getPlaceUnitId());
                    tbUnitSalePlan.setCategoryId(tbMain.getCategoryId());
                    tbUnitSalePlan.setSalePlanMainId(tbMain.getId());
                    tbUnitSalePlan.setSaleId(CommonUtils.createSaleID(tbMain.getPlaceUnitId(), tbUnitSalePlan1.getDate(), tbMain.getStartTime(),tbMain.getEndTime()));
                    tbUnitSalePlan.setPlaceUnitName(tbMain.getPlaceUnitName());
                    tbUnitSalePlan.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                    tbUnitSalePlan.setStartTime(tbMain.getStartTime());
                    tbUnitSalePlan.setEndTime(tbMain.getEndTime());
                    tbUnitSalePlan.setPrice(tbMain.getPrice());
                    tbUnitSalePlan.setMemberPrice(tbMain.getMemberPrice());
                    tbUnitSalePlan.setIsEffective(Constants.IS_ENABLE_TRUE);
                    tbUnitSalePlan.setVersion(tbMain.getVersion());

                    tbUnitSalePlan.setUnitType(tbMain.getUnitType());   // 确定场地类型

                    if (UNIT_TYPE_COMBINE.equals(tbUnitSalePlan.getUnitType())) {
                        PlaceCombinedUnitVo thisCU = CUMap.get(tbMain.getPlaceUnitId());
                        if (thisCU == null || thisCU.getBaseUnits() == null) {
                            continue;
                        }

                        String baseUnits = thisCU.getBaseUnits();
                        List<Integer> baseUnitIds = PlaceUtil.splitIds(baseUnits);
                        if (baseUnitIds == null || baseUnitIds.size() <= 0) {
                            continue;
                        }

                        List<String> saleIds = new ArrayList<>();
                        for (Integer buId : baseUnitIds) {
                            saleIds.add(CommonUtils.createSaleID(buId, tbUnitSalePlan1.getDate(), tbMain.getStartTime(),tbMain.getEndTime()));
                        }
                        tbUnitSalePlan.setSubSaleplans(StringUtil.join("|", saleIds));
                    }

                    resultList.add(tbUnitSalePlan);
                    tbMainList.add(tbMain);
                }
            }
        }
        Map<String, TbBizPlaceUnitSalePlan> resultMap = new HashMap();
        //去除重复销售计划
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : resultList) {
            if (!resultMap.containsKey(tbBizPlaceUnitSalePlan.getSaleId())) {
                resultMap.put(tbBizPlaceUnitSalePlan.getSaleId(), tbBizPlaceUnitSalePlan);
            }
        }
        List<TbBizPlaceUnitSalePlan> districtList = new ArrayList<>();
        for (Map.Entry<String, TbBizPlaceUnitSalePlan> entry : resultMap.entrySet()) {
            districtList.add(entry.getValue());
        }

        // 不要存在重叠
        APIResponse apiResponse = placeOrderService.salePlansVerification(districtList);
        if (apiResponse != null) {
            return APIResponse.returnFail("要包场的场地间存在组合-子场重叠");
        }

        try {
            APIResponse response = createBookForMember(reqBillingInfo, districtList,tbMainList);
            if (addTbUnitSalePlan(districtList) && response.isRet()) {
                TbBizPlacePrivateOrder tbBizPlacePrivateOrder = (TbBizPlacePrivateOrder)response.getData();
                PlacePrintVo placePrintVo = new PlacePrintVo();
                placePrintVo.setIsMember(PlaceConstants.YES);
                placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
                placePrintVo.setPlacePrivateOrderId(tbBizPlacePrivateOrder.getPlaceOrderId());
                return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
            }
        } catch (Exception e) {
            throw e;
        }
        return APIResponse.returnFail("会员包场失败");
    }

    @Override
    public APIResponse<?> addHibirdLog(ReqHibirdLog reqHibirdLog) {
        int flag = this.tbBusinessHibirdLogMapper.insertSelective(reqHibirdLog);
        if (flag == 0) {
            return APIResponse.returnFail("增加日志(tb_business_hibird_log)失败, ReqHibirdLog{}", JSON.toJSONString(reqHibirdLog));
        } else {
            return APIResponse.returnSuccess("增加日志(tb_business_hibird_log)成功");
        }
    }

    /**
     * 会员包场生成订单
     *
     * @param reqBillingInfo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> createBookForMember(ReqBillingInfo reqBillingInfo,
                                       List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans,
                                       List<TbBizPlaceUnitSalePlanMain> tbMainList) throws Exception {
        BigDecimal receivedAmount = new BigDecimal(reqBillingInfo.getReceivedAmount());
        List<String> weekList = new ArrayList();
        List<Integer> weeks = reqBillingInfo.getWeek();
        for (Integer list1 : weeks) {
            String para = list1.toString();
            weekList.add(para);
        }

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return APIResponse.returnFail("销售计划为空");
        }
        String orderid = baseService.getBizOrderId(reqBillingInfo.getCreateUid());
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = baseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
                reqBillingInfo.getCreateUid(), orderid, PlaceConstants.PRIVATE_USE_TYPE,reqBillingInfo,PlaceConstants.PRIVATE_USE_TYPE);//1 为包场会员价
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
            return APIResponse.returnFail("生成订单明细失败");
        }
        BigDecimal singlePrice = new BigDecimal(0);
        BigDecimal totalPrice = new BigDecimal(0);
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItemsPrice = baseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
                reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.PRIVATE_USE_TYPE);//普通价
        BigDecimal notMemberPrice = new BigDecimal(0);
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItemsPrice) {
            notMemberPrice = notMemberPrice.add(item.getSalePrice());
        }
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
            //插入明细
            singlePrice = item.getSalePrice();
            totalPrice = totalPrice.add(item.getSalePrice());
        }
        if (!StringUtils.isEmpty(reqBillingInfo.getMemberCardId())){
            TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqBillingInfo.getMemberCardId());
            if (!StringUtils.isEmpty(tbBizPlaceMemberCard)){
                for(TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain : tbMainList){
                    //会员卡可用时间校验
                    boolean flag1 = DateUtils.dateCompare(tbBizPlaceUnitSalePlanMain.getStartTime(), tbBizPlaceMemberCard.getAvailableStartTime(), true);//销售计划开始时间>=会员卡优惠开始时间返回true
                    boolean flag2 = DateUtils.dateCompare(tbBizPlaceMemberCard.getAvailableEndTime(), tbBizPlaceUnitSalePlanMain.getEndTime(), true);//会员卡优惠结束时间>=销售计划结束时间返回true
                    if (!(flag1 && flag2)) {
                        throw new Exception("您选择的会员卡仅支持" + DateTimeUtils.convertDate2String("HH:mm:ss", tbBizPlaceMemberCard.getAvailableStartTime()) + "-" + DateTimeUtils.convertDate2String("HH:mm:ss", tbBizPlaceMemberCard.getAvailableEndTime()) + "时间段的场馆费用支付");
                    }
                }
                if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){//折扣卡 ,储值折扣打折
                    //取折扣
                    BigDecimal discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount().intValue());
                    //打折扣
                    totalPrice = totalPrice.multiply(discount.divide(new BigDecimal(100)));
                }
            }
        }
        //插入父订单
        TbBizPlacePrivateOrder tbBizPlaceOrder = new TbBizPlacePrivateOrder();
        tbBizPlaceOrder.setPlaceOrderId(orderid);
        tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
        tbBizPlaceOrder.setCustomerName(reqBillingInfo.getName());
        tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
        tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
        tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
        tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
        tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
        tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
        tbBizPlaceOrder.setPaymentTime(new Date());
        tbBizPlaceOrder.setDebit(notMemberPrice);
        tbBizPlaceOrder.setDate(new Date());
        tbBizPlaceOrder.setEndTime(new Date());
        tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
        tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
        tbBizPlaceOrder.setParentId(0);
        tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
        tbBizPlaceOrder.setStartDate(DateUtils.transferLongToDate(reqBillingInfo.getStartDate()));
        tbBizPlaceOrder.setEndDate(DateUtils.transferLongToDate(reqBillingInfo.getEndDate()));
        tbBizPlaceOrder.setWeeks(JSON.toJSONString(weeks));
        tbBizPlaceOrder.setHandAdjustAmount(receivedAmount.subtract(totalPrice));
        tbBizPlaceOrder.setUseType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
        if (!StringUtils.isEmpty(reqBillingInfo.getExpression())){
            tbBizPlaceOrder.setExpression(reqBillingInfo.getExpression());
        }else{
            tbBizPlaceOrder.setExpression("");
        }
        Integer porderid = 0;
        if (this.tbBizPlacePrivateOrderMapper.insertSelective(tbBizPlaceOrder) != 0) {
            porderid = tbBizPlaceOrder.getId();
            logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(tbBizPlaceOrder));
        }

        //获取会员卡
        TbBizPlaceMemberCard tbBizPlaceMemberCard = null;
        if(!StringUtils.isEmpty(reqBillingInfo.getMemberCardId())){
            tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqBillingInfo.getMemberCardId());
            BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
            BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
            BigDecimal zeroAmount = new BigDecimal(0);
            if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE){//储值卡
                //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
                if (!StringUtils.isEmpty(initAmount) && !StringUtils.isEmpty(receivedAmount)){
                    //会员卡上的本金大于等于消费金额
                    if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
                        tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount));
                    }
                    else{
                        //会员卡上的本金+赠送金额大于等于消费金额
                        if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount.doubleValue()){
                            BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount.subtract(initAmount));
                            tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
                            tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
                        }else{
                            throw new Exception("请充值会员卡！");
                        }
                    }
                }
            }
            else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT){//折扣卡
                //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
                if (!StringUtils.isEmpty(initAmount) && !StringUtils.isEmpty(receivedAmount)){
                    //会员卡上的本金大于等于消费金额
                    if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
                        tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount));
                    }else{
                        throw new Exception("请充值会员卡！");
                    }
                }
            }
            else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT){//储值折扣卡
                //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
                if (!StringUtils.isEmpty(initAmount) && !StringUtils.isEmpty(receivedAmount)){
                    //会员卡上的本金大于等于消费金额
                    if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
                        tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(receivedAmount));
                    }
                    else{
                        //会员卡上的本金+赠送金额大于等于消费金额
                        if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount.doubleValue()){
                            BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount.subtract(initAmount));
                            tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
                            tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
                        }else{
                            throw new Exception("请充值会员卡！");
                        }
                    }
                }
            }
            tbBizPlaceMemberCard.setUpdateTime(new Date());
            int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
            if (flag1 == 1) {
                logger.debug("-------------------会员包场会员卡余额更新完毕-------------");
                //Todo 打折日志记录    折扣前会员价，折扣后价格
                TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
                tbBizPlaceMemberOpHistory.setCreateUid(reqBillingInfo.getCreateUid());
                tbBizPlaceMemberOpHistory.setPlaceId(reqBillingInfo.getPlaceId());
                tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
                tbBizPlaceMemberOpHistory.setAmount(receivedAmount);
                tbBizPlaceMemberOpHistory.setCreateTime(new Date());
                tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
                //TODO 生成流水号
                tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqBillingInfo.getPlaceId()));
                tbBizPlaceMemberOpHistory.setOrderNo(orderid);
                tbBizPlaceMemberOpHistory.setOpTypeName("商家端-" + baseService.getCommonDataCache("cagetory"
                        + reqBillingInfo.getCategoryId().toString()) + "场地费用");
                if (!StringUtils.isEmpty(reqBillingInfo.getContactInformation())
                        && !StringUtils.isEmpty(reqBillingInfo.getName())) {
                    Integer uid = placeMemberService.getUidByNameAndPhone(reqBillingInfo.getName(),
                            reqBillingInfo.getContactInformation());
                    tbBizPlaceMemberOpHistory.setUid(uid);
                }
                tbBizPlaceMemberOpHistory.setUserName(reqBillingInfo.getName());
                tbBizPlaceMemberOpHistory.setMobile(reqBillingInfo.getContactInformation());
                TbBizPlaceMemberCard tbBizPlaceMemberCard1 =
                        tbBizPlaceMemberCardMapper.selectByPrimaryKey(reqBillingInfo.getMemberCardId());
                tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
                tbBizPlaceMemberOpHistory.setMemo(reqBillingInfo.getMemo());
                tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
                tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
                tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
                tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
                tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
                tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
                tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
                tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard1.getCardTypeId());
                tbBizPlaceMemberOpHistory.setPayType(reqBillingInfo.getAdminPayType());
                tbBizPlaceMemberOpHistory.setAdminPayType(PayTypeEnum.getEnum(reqBillingInfo.getAdminPayType()).getUnifiedId());
                tbBizPlaceMemberOpHistory.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());//后台包场
                int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
                if (flag2 == 1) {
                    logger.debug("-------------------会员包场操作记录完毕-------------");
                }
            }

            TbBizPlace place=placeBaseService.getPlaceById(reqBillingInfo.getPlaceId());
            List<String> mobileList=new ArrayList<>();
            List<String> paramList=new ArrayList<>();
            //成功消费发送短信提醒
            String[] args = new String[7];
            args[0] = place != null ? place.getName() : "";
            args[1] = tbBizPlaceMemberCard != null ? tbBizPlaceMemberCard.getCardName() : "";
            args[2] = DateUtils.getCurrentTime();
            args[3] ="固定场";
            args[4] = receivedAmount != null ? receivedAmount.toString()+"元" : "";
            args[5]=tbBizPlaceMemberCard!=null?tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()).toString()+"元":"";
           // args[6]= place!=null?place.getPhone():"";
            // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
            TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(reqBillingInfo.getPlaceId());
            if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
                args[6]=placeAttach.getBookingConsultPhone();
            } else {
                // 获取系统配置的百灵鸟客服热线
                TbCommonParameter parameterVo = baseServiceimpl.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                args[6]=parameterVo!=null?parameterVo.getParameterValue():"";
            }
            mobileList.add(reqBillingInfo.getContactInformation());
            paramList.addAll(Arrays.asList(args));
            try{
                //placeTicketService.asyncSendSms(reqBillingInfo.getContactInformation(), SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, args, true);
                placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
            }catch(java.lang.Exception e){
                logger.info("短信发送失败-------->"+e.getMessage());
            }
        }
        //按日期插入订单明细数据
        Date startDate = new Date(reqBillingInfo.getStartDate());
        Date endDate = new Date(reqBillingInfo.getEndDate());
        double discount1 = StringUtils.isEmpty(tbBizPlaceMemberCard.getDiscount()) ? 100 : tbBizPlaceMemberCard.getDiscount();
        Map map = addOrderDetail(tbBizPlaceUnitSalePlans, startDate, endDate, reqBillingInfo, porderid, weeks, discount1,tbBizPlaceMemberCard,tbBizPlaceOrder);
        if (MapUtils.isEmpty(map)) {
            return APIResponse.returnFail("批量生产预订单失败");
        }
        List<TbBizPlaceOrder> orders = new ArrayList<>();
        List<TbBizPlaceOrderItem> items = new ArrayList<>();
        List<TbBizPlacePayItem> pays = new ArrayList<>();
        orders = (List<TbBizPlaceOrder>) MapUtils.getObject(map, "orders");
        items = (List<TbBizPlaceOrderItem>) MapUtils.getObject(map, "items");
        pays = (List<TbBizPlacePayItem>) MapUtils.getObject(map, "pays");

        for (TbBizPlaceOrder order : orders) {
            order.setEnableRefund(reqBillingInfo.getEnableRefund().byteValue());
        }
        int memberUid = placeMemberService.getUidByNameAndPhone(null, reqBillingInfo.getContactInformation());

        //记录未调价的订单明细
        List<TbBizPlaceOrderItem> oldOrderItems = new ArrayList<>();
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : items ){
            TbBizPlaceOrderItem tbBizPlaceOrderItem1 = new TbBizPlaceOrderItem();
            BeanUtils.copyProperties(tbBizPlaceOrderItem,tbBizPlaceOrderItem1);
            oldOrderItems.add(tbBizPlaceOrderItem1);
        }

        //调整金额  计算
        this.calcAmount(orders,items,pays,reqBillingInfo,tbBizPlaceOrder);


        //修改支付明细--现在改为按  订单明细-->支付明细
        List<TbBizPlacePayItem> placePayItemList = iBaseService.convertOrderPayItem(items, reqBillingInfo.getAdminPayType(), tbBizPlaceMemberCard);
        //生成订单折扣明细
        List<TbBizPlaceOrderDiscountItem> placeOrderDiscountItemList =  this.createBlockOrderDiscountItem(oldOrderItems, items, tbBizPlaceMemberCard);

        //add to db
        boolean flag = addOrders(orders, items, placePayItemList, placeOrderDiscountItemList, reqBillingInfo, memberUid);
        if (!flag) {
            throw new Exception("保存失败");
        }

        Map orderItemsMap = this.getTbBizPlaceItemListByPlaceOrderId(items);
        //插入支付流水
        List<ReqOrderHistory> reqOrderHistoryList = new ArrayList<>();
        for (TbBizPlaceOrder tbBizPlaceOrderTemp : orders){
            List<TbBizPlaceOrderItem> singleTbBizPlaceOrderItems = (List<TbBizPlaceOrderItem>)orderItemsMap.get(tbBizPlaceOrderTemp.getPlaceOrderId());
            List<ReqOrderHistory> singleOrderHistory = placeOrderUtilService.tbBizPlaceOrderItem2ReqOrderHistory(tbBizPlaceOrderTemp,singleTbBizPlaceOrderItems,(byte)0,(byte)0,tbBizPlaceMemberCard);
            reqOrderHistoryList.addAll(singleOrderHistory);
        }
        if (CollectionUtils.isNotEmpty(reqOrderHistoryList)){
            placeOrderUtilService.shoppingCartOrderInsertOrderHistory(reqOrderHistoryList);
        }
        return APIResponse.returnSuccess(tbBizPlaceOrder);
    }

    /*public APIResponse<?> createBookForMember1(ReqBillingInfo reqBillingInfo) {
        String[] unitids = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
        if (StringUtils.isEmpty(unitids) && unitids.length > 0) {
            return APIResponse.returnFail("unitIds is null");
        }
        List unitidss = new ArrayList();
        for (int i = 0, len = unitids.length; i < len; i++) {
            unitidss.add(unitids[i]);
        }
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        example.createCriteria().andSaleIdIn(unitidss);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return APIResponse.returnFail("PlaceUnitSalePlans is null");
        }
        String orderid = baseService.getBizOrderId(reqBillingInfo.getCreateUid());
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = baseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
                reqBillingInfo.getCreateUid(), orderid, PlaceConstants.PRIVATE_USE_TYPE);//1 为包场会员价
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
            return APIResponse.returnFail("PlaceOrderItems is null");
        }
        BigDecimal price = new BigDecimal(0);

        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
            //插入明细
            baseService.saveTbBizpPlaceOrderItem(item);
            logger.debug("===================插入明细数据:TbBizPlaceOrderItem:{}", JSON.toJSONString(item));
            price = price.add(item.getSalePrice());
        }
        //获取会员卡
        if(!StringUtils.isEmpty(reqBillingInfo.getMemberCardId())){
            TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqBillingInfo.getMemberCardId());
            BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
            BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
            //取折扣
            BigDecimal discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount().intValue());
            //打折扣
            price = price.multiply(discount.divide(new BigDecimal(100)));
            //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
            if (!StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusAmount()) && !StringUtils.isEmpty(price)){
                //会员卡上的本金大于等于消费金额
                if (tbBizPlaceMemberCard.getSurplusAmount().doubleValue() >= price.doubleValue()){
                    tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(price));
                }
                else{
                    //会员卡上的本金+赠送金额大于等于消费金额
                    if (tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getGiveAmount()).doubleValue() >= price.doubleValue()){
                        tbBizPlaceMemberCard.setSurplusAmount(new BigDecimal(0));
                        tbBizPlaceMemberCard.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().subtract(price.subtract(tbBizPlaceMemberCard.getSurplusAmount())));
                    }else{
                        return APIResponse.returnFail("请充值会员卡！");
                    }
                }
            }
            tbBizPlaceMemberCard.setCreateUid(reqBillingInfo.getCreateUid());
            tbBizPlaceMemberCard.setUpdateTime(new Date());
            int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
            if (flag1 ==1 ){
                logger.debug("-------------------会员包场会员卡余额更新完毕-------------");
                //Todo 打折日志记录    折扣前会员价，折扣后价格
                TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
                tbBizPlaceMemberOpHistory.setCreateUid(reqBillingInfo.getCreateUid());
                tbBizPlaceMemberOpHistory.setPlaceId(reqBillingInfo.getPlaceId());
                tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
                tbBizPlaceMemberOpHistory.setAmount(new BigDecimal(0).subtract(price));
                tbBizPlaceMemberOpHistory.setCreateTime(new Date());
                tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
                //TODO 生成流水号
                tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqBillingInfo.getPlaceId()));
                tbBizPlaceMemberOpHistory.setOrderNo(orderid);
                tbBizPlaceMemberOpHistory.setOpTypeName("包场消费");
                if (!StringUtils.isEmpty(reqBillingInfo.getContactInformation()) && !StringUtils.isEmpty(reqBillingInfo.getName())){
                    Integer uid = placeMemberService.getUidByNameAndPhone(reqBillingInfo.getName(),reqBillingInfo.getContactInformation());
                    tbBizPlaceMemberOpHistory.setUid(uid);
                }
                tbBizPlaceMemberOpHistory.setUserName(reqBillingInfo.getName());
                tbBizPlaceMemberOpHistory.setMobile(reqBillingInfo.getContactInformation());
                TbBizPlaceMemberCard tbBizPlaceMemberCard1 = tbBizPlaceMemberCardMapper.selectByPrimaryKey(reqBillingInfo.getMemberCardId());
                tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
                tbBizPlaceMemberOpHistory.setMemo(reqBillingInfo.getMemo());
                tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
                tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
                tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
                tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
                tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
                tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
                tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);


                int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
                if (flag2 ==1 ) {
                    logger.debug("-------------------会员包场操作记录完毕-------------");
                }
            }
        }
        //插入订单
        TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

        tbBizPlaceOrder.setPlaceOrderId(orderid);
        tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
        tbBizPlaceOrder.setCustomerName(reqBillingInfo.getName());
        tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
        tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
        tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
        tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
        tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
        tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
        tbBizPlaceOrder.setPaymentTime(new Date());
        tbBizPlaceOrder.setDebit(price);
        tbBizPlaceOrder.setDate(new Date());
        tbBizPlaceOrder.setEndTime(new Date());
        tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
        tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
        if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) != 0) {
            logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(tbBizPlaceOrder));
            TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
            tbBizPlacePayItem.setPlaceOrderId(orderid);
            tbBizPlacePayItem.setAmount(price);
            tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
            tbBizPlacePayItem.setPayType(PlaceConstants.PAY_WAY_SCENEPAY);
            if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) != 0) {
                logger.debug("========================插入订单支付数据:TbBizPlacePayItem:{}",
                        JSON.toJSONString(tbBizPlacePayItem));
                //修改销售计划
                List<UnitSalePlan> list = new ArrayList<>();
                for (TbBizPlaceUnitSalePlan tsp : tbBizPlaceUnitSalePlans) {
                    UnitSalePlan up = new UnitSalePlan();
                    up.setSaleId(tsp.getSaleId());
                    list.add(up);
                }
                ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
                reqPlaceOrderListVo.setUnitSalePlanIdList(list);
                reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
                int flag = placeUnitSalePlanMapper.updateByPrimaryKeyList(reqPlaceOrderListVo);
                logger.debug("========================修改销售计划数据:ReqPlaceOrderListVo:{}",
                        JSON.toJSONString(reqPlaceOrderListVo));
                return APIResponse.returnSuccess();
            }
        }
        return APIResponse.returnFail("会员包场失败");
    }*/

    @Override
    public APIResponse<List<RespMemberCard>> billingPlaceGetMemberCardList(String userName, String phone,
                                                                                 Integer placeId, Integer categoryId) {
        return placeMemberService.billingPlaceGetMemberCardList(userName, phone, placeId, categoryId);
    }

    /**
     * 商家端支付方式
     *
     * @return
     */
    @Override
    public APIResponse<?> getAdminPayWaysDictDisplayName(Integer placeId, Integer userType, boolean isRecharge) {
        // payWay 默认:全部支付方式 1：散客支付方式 2：会员支付方式
        /*Map map = getDictDisplayName(PlaceConstants.PLACE_ADMIN_PAY_WAYS);
        if (!StringUtils.isEmpty(userType)){
            if (userType.intValue() == 1){
                //散客支付方式   现金／微信扫码／支付宝扫码／银联／与外部单位结算／与总部内部核算
                Iterator iterator = map.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = (String) iterator.next();
                    //排除会员卡，场馆老板结算
                    if (PlaceConstants.PAY_WAY_FOR_CARD.toString().equals(key)
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS.equals(key)) {
                        iterator.remove();
                        map.remove(key);
                    }
                }
            }
            if (userType.intValue() == 2){
                //会员支付方式   会员卡/与场馆老板结算／与总部内部核算
                Iterator iterator = map.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = (String) iterator.next();
                    if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_OUTSIDE.equals(key)
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_UNIONPAY.equals(key)
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(key)
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(key)
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_CASH.equals(key)) {
                        iterator.remove();
                        map.remove(key);
                    }
                }
            }
        }else{
            if (isRecharge){
                //去除  会员卡，场馆老板结算，与外部公司结算，与公司内部核算
                Iterator iterator = map.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = (String) iterator.next();
                    if (PlaceConstants.PAY_WAY_FOR_CARD.toString().equals(key)
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS.equals(key)
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_OUTSIDE.equals(key)
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_INNER.equals(key)) {
                        iterator.remove();
                        map.remove(key);
                    }
                }
            }
        }
        return APIResponse.returnSuccess(map);*/
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeId);
        if (StringUtils.isEmpty(tbBizPlace)){
            return APIResponse.returnFail("系统场馆不存在");
        }
        if (StringUtils.isEmpty(tbBizPlace.getBusinessMode())){
            return APIResponse.returnFail("场馆经营方式数据为空");
        }

        TbBizPlacePayTypeExample tbBizPlacePayTypeExample = new TbBizPlacePayTypeExample();
        TbBizPlacePayTypeExample.Criteria tbBizPlacePayTypeCriteria = tbBizPlacePayTypeExample.createCriteria();
        tbBizPlacePayTypeCriteria.andTagGroupEqualTo(PlaceConstants.PLACE_ADMIN_PAY_WAYS);
        tbBizPlacePayTypeCriteria.andParaBusinessModeEqualTo(tbBizPlace.getBusinessMode().intValue());
        tbBizPlacePayTypeCriteria.andStatusEqualTo(PlaceConstants.YES);
        if (!StringUtils.isEmpty(userType)){
            if (userType.intValue() == 1){
                //散客支付方式   现金／微信扫码／支付宝扫码／银联／与外部单位结算／与总部内部核算
                tbBizPlacePayTypeCriteria.andParaIsGuestEqualTo(PlaceConstants.YES.intValue());
            }
            if (userType.intValue() == 2){
                //会员支付方式   会员卡/与场馆老板结算／与总部内部核算
                tbBizPlacePayTypeCriteria.andParaIsMemberEqualTo(PlaceConstants.YES.intValue());
            }
        }else{
            if (isRecharge){
                //去除  会员卡，场馆老板结算，与外部公司结算，与公司内部核算
                tbBizPlacePayTypeCriteria.andParaCardEqualTo(PlaceConstants.YES.intValue());
            }
        }
        List<TbBizPlacePayType> result = tbBizPlacePayTypeMapper.selectByExample(tbBizPlacePayTypeExample);
        //支付方式按优先级排序
        ComparatorChain chain = new ComparatorChain();
        chain.addComparator(new BeanComparator("priority"),true);//true,fase正序反序
//        chain.addComparator(new BeanComparator("dataKey"));
        Collections.sort(result,chain);

//        Map<String, String> map = new LinkedHashMap<String, String>();
//        for (TbBizPlacePayType tbBizPlacePayType : result) {
//            map.put(tbBizPlacePayType.getDataKey(), tbBizPlacePayType.getDataValue());
//        }

        return APIResponse.returnSuccess(result);
    }

    @Override
    public APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> placeSearch(ReqSearchVo reqSearchVo) {
        if (reqSearchVo.getSearchType().intValue() > SearchTypeEnum.MAP_MODE.getId()) {
            reqSearchVo.setPageNum(reqSearchVo.getPageNum() * reqSearchVo.getPageSize());
            return this.searchH5PlaceList(reqSearchVo);
        }

        // 增加用户已经预定的场地
       /* HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer) httpServletRequest.getAttribute("uid");*/
        Integer userId = reqSearchVo.getUid();
//                    userId = 3706;
        if (!StringUtils.isEmpty(userId) && userId != 0 && !StringUtils.isEmpty(reqSearchVo.getSortType()) &&
                reqSearchVo.getSortType().intValue() == SortTypeEnum.HISTORY_ORDERS.getId()) {
            //获取用户订单列表
            APIResponse apiResponse = this.searchPlaceList(userId, reqSearchVo);

            if (!StringUtils.isEmpty(apiResponse.getData())) {
                return apiResponse;
            }
            if (StringUtils.isEmpty(apiResponse.getData()) && reqSearchVo.getIsFirst() == 1) {
                return this.searchPlaceList(reqSearchVo);
            }
            if (StringUtils.isEmpty(apiResponse.getData()) && reqSearchVo.getIsFirst() == 0) {
                return APIResponse.returnSuccess(null);
            }
        }

        if (PlaceConstants.SOLR_TYPE_QUERY.equals(baseServiceimpl.getPlaceSearchType())) { //1；开启solr查询 2：直接查询数据库
            return this.searchPlaceList(reqSearchVo);
        } else if (PlaceConstants.DB_TYPE_QUERY.equals(baseServiceimpl.getPlaceSearchType())) {
            reqSearchVo.setPageNum(reqSearchVo.getPageNum() * reqSearchVo.getPageSize());
            return this.searchByDb(reqSearchVo);
        } else {
            return this.searchPlaceList(reqSearchVo);
        }
    }

    @Override
    public APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> newPlaceSearch(ReqSearchVo reqSearchVo) {
        if (reqSearchVo.getSearchType().intValue() > SearchTypeEnum.MAP_MODE.getId()) {
            reqSearchVo.setPageNum(reqSearchVo.getPageNum() * reqSearchVo.getPageSize());
            return this.searchH5PlaceList(reqSearchVo);
        }

        // 增加用户已经预定的场地
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer) httpServletRequest.getAttribute("uid");
        userId = 1056;
        if (null != userId && 0 != userId){
            //获取用户订场记录
            List<Integer> placeIds = new ArrayList<>();
            TbBizPlaceOrderExample orderExample = new TbBizPlaceOrderExample();
            orderExample.createCriteria().andUidEqualTo(userId).andIsEffectiveEqualTo(PlaceConstants.IS_EFFECTIVE_YES)
                    .andCategoryIdEqualTo(reqSearchVo.getCategoryId());
            List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(orderExample);
            if (CollectionUtils.isNotEmpty(tbBizPlaceOrders)){
                for (TbBizPlaceOrder tbBizPlaceOrder : tbBizPlaceOrders){

                    TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlaceOrder.getPlaceId());
                    if (null == tbBizPlace){
                        continue;
                    }
                    if (placeIds.contains(tbBizPlace.getId())){
                        continue;
                    }
                    if (null != reqSearchVo.getDistrictId()){
                        if (reqSearchVo.getDistrictId().intValue() == tbBizPlace.getDistrictId().intValue()){
                            placeIds.add(tbBizPlace.getId());
                        }
                    }else if (null != reqSearchVo.getCityId()
                            && reqSearchVo.getCityId().intValue() == tbBizPlace.getCityId().intValue()){
                        placeIds.add(tbBizPlace.getId());
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(placeIds)){
                reqSearchVo.setPlaceIds(placeIds);
            }
        }

        if (PlaceConstants.SOLR_TYPE_QUERY.equals(baseServiceimpl.getPlaceSearchType())) { //1；开启solr查询 2：直接查询数据库
            return this.searchPlaceListNew(reqSearchVo);
        } else if (PlaceConstants.DB_TYPE_QUERY.equals(baseServiceimpl.getPlaceSearchType())) {
            reqSearchVo.setPageNum(reqSearchVo.getPageNum() * reqSearchVo.getPageSize());
            return this.searchByDb(reqSearchVo);
        } else {
            return this.searchPlaceList(reqSearchVo);
        }
    }

    private APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> searchPlaceListNew(ReqSearchVo reqSearchVo) {
        StopWatch stopWatch = new StopWatch();
        logger.info("===================搜索条件===========reqSearchVo: {}", JSON.toJSONString(reqSearchVo));
        stopWatch.start("1");
        ReqPlaceSearchInfo reqPlaceSearchInfo = this.searchService.getReqPlaceSearchInfo(reqSearchVo);
        logger.info("===================转换搜索对象===========ReqPlaceSearchInfo:{}",
                JSON.toJSONString(reqPlaceSearchInfo));
//        if (StringUtils.isEmpty(reqSearchVo.getPageNum()) || reqSearchVo.getPageNum().intValue()==Constants.DEFAULT_PAGE_NUM){
//            reqSearchVo.setPageNum(Constants.DEFAULT_PAGE_INDEX);
//        }
        stopWatch.stop();
        stopWatch.start("2");
        ReqPlaceSearchInfoNew reqPlaceSearchInfoNew = new ReqPlaceSearchInfoNew();
        BeanUtils.copyProperties(reqPlaceSearchInfo, reqPlaceSearchInfoNew);
        reqPlaceSearchInfoNew.setStartPosition(reqSearchVo.getStartPosition());
        reqPlaceSearchInfoNew.setPlaceIds(reqSearchVo.getPlaceIds());

        APIResponse<SearchResponses<List<PlaceSearchResponse>>> response = this.searchService.searchPlaceInfoListNew(reqPlaceSearchInfoNew);
        logger.info("===================调用搜索引擎===========APIResponse<List<PlaceSearchResponse>>:{}",
                JSON.toJSONString(response));
        stopWatch.stop();
        stopWatch.start("3");
        if (!response.isRet()) {
            logger.error("===================调用搜索引擎失败===========ReqPlaceSearchInfo:{}",
                    JSON.toJSONString(reqPlaceSearchInfo));
            return APIResponse.returnFail("没有记录");
        }
        List<PlaceSearchResponse> list = response.getData().getData();
        if (CollectionUtils.isEmpty(list)) {
            logger.warn("===================调用搜索引擎查询无结果===========ReqPlaceSearchInfo:{}",
                    JSON.toJSONString(reqPlaceSearchInfo));
            return APIResponse.returnSuccess(null);
        }
        Integer total = response.getData().getTotal();
        total = 1000;
        //传入reqSearchVo
        Integer startPosition = response.getData().getPageStart();
        List<RespBizPlaceBaseInfo> respBizPlaceBaseInfos = this.searchService.getSearchBizPlaceBaseInfos(list,
                reqSearchVo, startPosition);
        Integer pageNum = reqSearchVo.getPageNum();
        if (pageNum == null) {
            pageNum = Constants.DEFAULT_PAGE_NUM;
        }

        Integer pageSize = reqSearchVo.getPageSize();
        if (pageSize == null) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        PageObj<List<RespBizPlaceBaseInfo>> pageObj = PageObj.create(total, pageNum,
                pageSize, respBizPlaceBaseInfos);
        stopWatch.stop();
        logger.info(stopWatch.prettyPrint());
        return APIResponse.returnSuccess(pageObj);
    }

    @Override
    public APIResponse<?> recommendPlaceByUid(Integer userId, ReqSearchVo reqSearchVo) {
        //调用搜索引擎返回距离为150米以内开始时间2小时以内的100个场馆
        reqSearchVo.setPageSize(100);
        reqSearchVo.setDate(new Date());
        Double area = baseServiceimpl.getPlaceRecommendArea();
        if (area == null || area <= 0d){
            area = 150d;
        }
        reqSearchVo.setArea(area / 1000d);
        reqSearchVo.setSearchType(SearchTypeEnum.LAST_UPDATE_TIME.getId());
        reqSearchVo.setIsShelves(PlaceConstants.PLACE_GOODS_STATUS_SALE);
        reqSearchVo.setSortType(SortTypeEnum.LOWEST_PRICE.getId());

        APIResponse<PageObj<List<RespBizPlaceBaseInfo>>> response = this.placeSearch(reqSearchVo);
        List<RespBizPlaceBaseInfo> respBizPlaceBaseInfos = null;
        if (!response.isRet()){
            return APIResponse.returnFail("搜索失败");
        }

        PageObj<List<RespBizPlaceBaseInfo>> pageObj = response.getData();
        if (null != pageObj){
            respBizPlaceBaseInfos = pageObj.getItems();
            if (CollectionUtils.isNotEmpty(respBizPlaceBaseInfos)){
                RespRecommendPlace respRecommendPlace = new RespRecommendPlace();
                //用户未登录，遵循第一条场景。
                if (null == userId || userId == 0){
                    BeanUtils.copyProperties(respBizPlaceBaseInfos.get(0), respRecommendPlace);
                    return APIResponse.returnSuccess(respRecommendPlace);
                }
                //获取用户2小时以内的场馆,没有返回第一个场馆信息
                List<RespRecommendPlaceOrder> tbBizPlaceUnitSalePlans = placeMapper.orderPlaceByUid(userId);
                if(CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)){
                    BeanUtils.copyProperties(respBizPlaceBaseInfos.get(0), respRecommendPlace);
                    return APIResponse.returnSuccess(respRecommendPlace);
                }
                Integer placeId = null;
                List<RespRecommendPlaceOrder> list = new ArrayList<>();
                for(int i=0; i<respBizPlaceBaseInfos.size(); i++){
                    for (RespRecommendPlaceOrder order : tbBizPlaceUnitSalePlans){
                        placeId = order.getPlaceId();
                        if (respBizPlaceBaseInfos.get(i).getId().intValue() == placeId.intValue()){
                            list.add(order);
                        }
                    }
                }
                //返回订单信息
                if (CollectionUtils.isNotEmpty(list)){
                    respRecommendPlace.setRespRecommendPlaceOrders(list);
                    return  APIResponse.returnSuccess(respRecommendPlace);
                }else{
                    BeanUtils.copyProperties(respBizPlaceBaseInfos.get(0), respRecommendPlace);
                    return APIResponse.returnSuccess(respRecommendPlace);
                }
            }
        }

        return APIResponse.returnFail("没有搜索结果");
    }

    /**
     * 根据type获取字典类型
     *
     * @param type
     * @return
     */
    public Map<String, String> getDictDisplayName(String type) {
        HashMap<String, String> map = new HashMap<String, String>();
        DictExample dictExample = new DictExample();
        DictExample.Criteria dictCriteria = dictExample.createCriteria();
        dictCriteria.andTagGroupEqualTo(type);
        List<Dict> result = dictMapper.selectDataValueByExample(dictExample);
        for (Dict dict : result) {
            map.put(dict.getDataKey(), dict.getDataValue());
        }
        return map;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public APIResponse<?> placeBlockBook(ReqBillingInfo reqBillingInfo) throws Exception{
	        // 1.查询客户端返回时间段 周几 `place_id` `place_unit_id`  根据销售模板计算销售计划的总数
	        // 2.判断有的就更新  没有就插入
    	
    	    if (CollectionUtils.isEmpty(reqBillingInfo.getUnitSaleInfos())){
               return APIResponse.returnFail("场地信息必传");
            }
    	    
    	    List<String> reqSaleIdList = null;
	        if (!StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())) {
	            String[] saleIds = org.apache.commons.lang3.StringUtils.split(reqBillingInfo.getPlaceUnitId(), ",");
	            reqSaleIdList = Arrays.asList(saleIds);
	        }
	        if (CollectionUtils.isEmpty(reqSaleIdList)){
	            return APIResponse.returnFail("saleIds必传");
	        }
    	
	        //校验是否有存在不可售的销售计划（防止超卖情况）
	        PlaceBookAllCheckVo placeBookAllCheckVo = new PlaceBookAllCheckVo();
	        placeBookAllCheckVo.setPlaceId(reqBillingInfo.getPlaceId());
	        placeBookAllCheckVo.setCategoryId(reqBillingInfo.getCategoryId());
	        placeBookAllCheckVo.setEndDate(DateUtils.transferLongToDate(reqBillingInfo.getEndDate()));
	        placeBookAllCheckVo.setStartDate(DateUtils.transferLongToDate(reqBillingInfo.getStartDate()));
	        placeBookAllCheckVo.setTimeTypeList(reqBillingInfo.getWeek());
	        placeBookAllCheckVo.setPlaceUnitSaleInfoList(reqBillingInfo.getUnitSaleInfos());
	        
	        List<String> tbSaleIds = placeBlockBookingOrderMapper.checkBookAllOrder(placeBookAllCheckVo);
	       
	        tbSaleIds.retainAll(reqSaleIdList);//取交集
	        if (CollectionUtils.isNotEmpty(tbSaleIds)){
	            return APIResponse.returnFail("场地已被预定");
	        }

	        logger.debug("====================开始增加销售计划");
	        List<TbBizPlaceUnitSalePlan> resultList = new ArrayList<>();
	        
	        //包场增加销售计划
	        Date startDate = new Date(reqBillingInfo.getStartDate());
	        Date endDate = new Date(reqBillingInfo.getEndDate());

	        //获取日期内符合星期的销售列表
	        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = getTbBizPlaceUnitSalePlanByPlaceBoookAll(reqBillingInfo,
	                startDate, endDate);
	        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
	            return APIResponse.returnFail("选择的星期不在日期范围内");
	        }

	        //获取销售计划模板
	        List<String> types = new ArrayList<>();
	        for (Integer type : reqBillingInfo.getWeek()) {
	            types.add(type + "");
	        }
	        
	        TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
	        TbBizPlaceUnitSalePlanMainExample.Criteria mainCriteria = tbBizPlaceUnitSalePlanMainExample.createCriteria();
	        mainCriteria.andIsEffectiveEqualTo(Constants.IS_ENABLE_TRUE).andPlaceIdEqualTo(reqBillingInfo.getPlaceId())
	                .andPlaceUnitIdIn(reqBillingInfo.getUnitId())
	                .andCategoryIdEqualTo(reqBillingInfo.getCategoryId()).andTimeTypeIn(types);
	        
	        List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMains = tbBizPlaceUnitSalePlanMainMapper
	                .selectByExample(tbBizPlaceUnitSalePlanMainExample);
	        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMains)) {
	            logger.error("==========================没有销售计划模板 ReqPlaceSalePlan:{}",
	                    JSON.toJSONString(reqBillingInfo));
	            RespBizCodeInfo respBizCodeInfo = new RespBizCodeInfo();
	            respBizCodeInfo.setSuccess(false);
	            respBizCodeInfo.setGetCode(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getCode());
	            respBizCodeInfo.setGetId(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getId());
	            respBizCodeInfo.setGetLabel(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD.getLabel());
	            return APIResponse.returnSuccess(respBizCodeInfo);
	        }

	        // 查询该场馆的所有的组合场信息
	        List<PlaceCombinedUnitVo> allCUs = placeUCService.getCombinedUnits(reqBillingInfo.getPlaceId(), reqBillingInfo.getCategoryId(), null);
	        Map<Integer, PlaceCombinedUnitVo> cUMap = Maps.uniqueIndex(allCUs, new Function<PlaceCombinedUnitVo, Integer>() {
				@Override
				public Integer apply(PlaceCombinedUnitVo input) {
					return input.getId();
				}
			});

	        for (TbBizPlaceUnitSalePlan tbUnitSalePlan1 : tbBizPlaceUnitSalePlans) {
	            for (TbBizPlaceUnitSalePlanMain tbMain : tbBizPlaceUnitSalePlanMains) {
	                //去除销售计划模板中没有的数据
	                if (tbUnitSalePlan1.getPlaceUnitId().intValue() == tbMain.getPlaceUnitId().intValue() &&
	                        tbUnitSalePlan1.getTimeType().equals(tbMain.getTimeType())
	                        && (tbUnitSalePlan1.getStartTime().equals(tbMain.getStartTime())
	                        && tbUnitSalePlan1.getEndTime().equals(tbMain.getEndTime()))) {
	                	
	                    TbBizPlaceUnitSalePlan tbUnitSalePlan = new TbBizPlaceUnitSalePlan();
	                    BeanUtils.copyProperties(tbUnitSalePlan1, tbUnitSalePlan);
	                    tbUnitSalePlan.setPlaceId(tbMain.getPlaceId());
	                    tbUnitSalePlan.setPlaceUnitId(tbMain.getPlaceUnitId());
	                    tbUnitSalePlan.setCategoryId(tbMain.getCategoryId());
	                    tbUnitSalePlan.setSalePlanMainId(tbMain.getId());
	                    tbUnitSalePlan.setSaleId(CommonUtils.createSaleID(tbMain.getPlaceUnitId(), tbUnitSalePlan1.getDate(), tbMain.getStartTime(),tbMain.getEndTime()));
	                    //tbUnitSalePlan.setId(getPlaceSaleUnitId(tbUnitSalePlan.getSaleId()));
	                    tbUnitSalePlan.setPlaceUnitName(tbMain.getPlaceUnitName());
	                    
	                    tbUnitSalePlan.setStatus(PlaceConstants.PLACE_LOCk_STATUS);
	                    tbUnitSalePlan.setLockTime(new Date());
	                    
	                    tbUnitSalePlan.setStartTime(tbMain.getStartTime());
	                    tbUnitSalePlan.setEndTime(tbMain.getEndTime());
	                    tbUnitSalePlan.setPrice(tbMain.getPrice());
	                    tbUnitSalePlan.setMemberPrice(tbMain.getMemberPrice());
	                    tbUnitSalePlan.setIsEffective(Constants.IS_ENABLE_TRUE);
	                    tbUnitSalePlan.setVersion(tbMain.getVersion());
	                    tbUnitSalePlan.setUnitType(tbMain.getUnitType());   // 确定场地类型
	                    if (tbMain.getBundleNo() != null){
	                        if (tbMain.getBundleNo() == 0){
	                            tbUnitSalePlan.setBundleNo(0);
	                        } else {
	                            String bundleNo = tbMain.getPlaceUnitId()+""+tbMain.getBundleNo();
	                            tbUnitSalePlan.setBundleNo(Integer.valueOf(bundleNo));
	                        }
	                    }
	                    if (UNIT_TYPE_COMBINE.equals(tbUnitSalePlan.getUnitType())) {
	                        PlaceCombinedUnitVo thisCU = cUMap.get(tbMain.getPlaceUnitId());
	                        if (thisCU == null || thisCU.getBaseUnits() == null) {
	                            continue;
	                        }

	                        String baseUnits = thisCU.getBaseUnits();
	                        List<Integer> baseUnitIds = PlaceUtil.splitIds(baseUnits);
	                        if (baseUnitIds == null || baseUnitIds.size() <= 0) {
	                            continue;
	                        }

	                        List<String> saleIds = new ArrayList<>();
	                        for (Integer buId : baseUnitIds) {
	                            saleIds.add(CommonUtils.createSaleID(buId, tbUnitSalePlan1.getDate(), tbMain.getStartTime(),tbMain.getEndTime()));
	                        }
	                        tbUnitSalePlan.setSubSaleplans(StringUtil.join("|", saleIds));
	                    }

	                    resultList.add(tbUnitSalePlan);
	                }
	            }
	        }
	        Map<String, TbBizPlaceUnitSalePlan> resultMap = new HashMap();
	        //去除重复销售计划
	        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : resultList) {
	            if (!resultMap.containsKey(tbBizPlaceUnitSalePlan.getSaleId())) {
	                resultMap.put(tbBizPlaceUnitSalePlan.getSaleId(), tbBizPlaceUnitSalePlan);
	            }
	        }
	        List<TbBizPlaceUnitSalePlan> districtList = new ArrayList<>();
	        for (Map.Entry<String, TbBizPlaceUnitSalePlan> entry : resultMap.entrySet()) {
	            districtList.add(entry.getValue());
	        }

	        // 不要有重叠
	        APIResponse apiResponse = placeOrderService.salePlansVerification(districtList);
	        if (apiResponse != null) {
	            return APIResponse.returnFail("要包场的场地间存在组合-子场重叠");
	        }
	        
	        //生产预定订单
            APIResponse response = createBlockBook(reqBillingInfo, districtList,tbBizPlaceUnitSalePlanMains);
            if (response.isRet()) {
            	  updateTbUnitSalePlan(districtList);
            } else {
                return APIResponse.returnFail("包场预定失败:"+response.getErrmsg());
            }
			return APIResponse.returnSuccess("包场预定成功");
	}
    
    
    private Integer getPlaceSaleUnitId(String saleId){
    	TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
    	tbBizPlaceUnitSalePlanExample.createCriteria().andSaleIdEqualTo(saleId);
    	
    	List<TbBizPlaceUnitSalePlan>  tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample);
    	if (!CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanList)) {
			return tbBizPlaceUnitSalePlanList.get(0).getId();
		}
    	return null;
    }
    
    /**
     * 更新销售计划
     * 
     * @param tbBizPlaceUnitSalePlans
     * @return
     */
    
    
    private boolean updateTbUnitSalePlan(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans) throws Exception {

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return false;
        }
        for (TbBizPlaceUnitSalePlan tbSalePlan : tbBizPlaceUnitSalePlans) {
            TbBizPlaceUnitSalePlanExample tbSalePlanExample = new TbBizPlaceUnitSalePlanExample();
            TbBizPlaceUnitSalePlanExample.Criteria criteria = tbSalePlanExample.createCriteria();
            criteria.andPlaceIdEqualTo(tbSalePlan.getPlaceId()).andCategoryIdEqualTo(tbSalePlan.getCategoryId())
                    .andIsEffectiveEqualTo(Constants.IS_ENABLE_TRUE).andPlaceUnitIdEqualTo(tbSalePlan.getPlaceUnitId())
                    .andDateEqualTo(tbSalePlan.getDate()).andTimeTypeEqualTo(tbSalePlan.getTimeType())
                    .andStartTimeEqualTo(tbSalePlan.getStartTime())
                    .andEndTimeEqualTo(tbSalePlan.getEndTime());
            //tbSalePlanExample.setOrderByClause(" id for update ");
            
            List<TbBizPlaceUnitSalePlan> tbSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(tbSalePlanExample);
            
            if (CollectionUtils.isNotEmpty(tbSalePlans)) {
                for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbSalePlans){
                    if (tbBizPlaceUnitSalePlan.getStatus().intValue() != PlaceConstants.PLACE_PREORDER_STATUS.intValue()){
                        throw new Exception("您所选场地部分已经出售或者被锁场！建议确认场地锁场信息");
                    }
                }
                //更新之前加个状态判断  未预定 --> 已预订
                criteria.andStatusEqualTo(PlaceConstants.PLACE_PREORDER_STATUS);
                if (tbBizPlaceUnitSalePlanMapper.updateByExampleSelective(tbSalePlan, tbSalePlanExample) < 1){
                	throw new BizException("场地已被预定");
                }
                
            } else {
                try {
                    this.tbBizPlaceUnitSalePlanMapper.insertSelective(tbSalePlan);
                } catch (Exception e){
                    logger.warn("包场重复添加销售计划"+e.getMessage());
                    throw new Exception("尝试插入包场销售计划失败，回滚事务");
                }

                logger.debug("====================================增加销售计划 TbBizPlaceUnitSalePlan:{}",
                        JSON.toJSONString(tbSalePlan));
            }
        }
        return true;
    }
    
    private APIResponse<?> createBlockBook(ReqBillingInfo reqBillingInfo, List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans,
    		 List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMains)
            throws Exception {

        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return APIResponse.returnFail("销售计划为空");
        }

        String orderid = baseService.getBizOrderId(reqBillingInfo.getCreateUid());
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = baseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
                reqBillingInfo.getCreateUid(), orderid, PlaceConstants.PRIVATE_USE_TYPE,reqBillingInfo,PlaceConstants.PRIVATE_USE_TYPE);//1 为包场会员价
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
            return APIResponse.returnFail("订单明细为空");
        }
        BigDecimal price = new BigDecimal(0);
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
            //插入明细
            price = price.add(item.getSalePrice());
        }
        
        List<TbBizPlaceOrderItem> notMemberTbBizPlaceOrderItems = baseService.salePlans2OrderItem(tbBizPlaceUnitSalePlans,
                reqBillingInfo.getCreateUid(), orderid, PlaceConstants.BILLING_TYPE,reqBillingInfo,PlaceConstants.PRIVATE_USE_TYPE);//0 为普通价


        BigDecimal notMemberPrice = new BigDecimal(0);
        for (TbBizPlaceOrderItem item : notMemberTbBizPlaceOrderItems) {
            //订单价格
            notMemberPrice = notMemberPrice.add(item.getSalePrice());
        }
        BigDecimal totalPrice = notMemberPrice;
        //会员价格处理
        BigDecimal discount = new BigDecimal(100);
        TbBizPlaceMemberCard tbBizPlaceMemberCard = null;
        if (!StringUtils.isEmpty(reqBillingInfo.getMemberCardId())){
            tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqBillingInfo.getMemberCardId());
            if (!StringUtils.isEmpty(tbBizPlaceMemberCard)){
                for(TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain : tbBizPlaceUnitSalePlanMains){
                    //会员卡可用时间校验
                    boolean flag1 = DateUtils.dateCompare(tbBizPlaceUnitSalePlanMain.getStartTime(), tbBizPlaceMemberCard.getAvailableStartTime(), true);//销售计划开始时间>=会员卡优惠开始时间返回true
                    boolean flag2 = DateUtils.dateCompare(tbBizPlaceMemberCard.getAvailableEndTime(), tbBizPlaceUnitSalePlanMain.getEndTime(), true);//会员卡优惠结束时间>=销售计划结束时间返回true
                    if (!(flag1 && flag2)) {
                        throw new Exception("您选择的会员卡仅支持" + DateTimeUtils.convertDate2String("HH:mm:ss", tbBizPlaceMemberCard.getAvailableStartTime()) + "-" + DateTimeUtils.convertDate2String("HH:mm:ss", tbBizPlaceMemberCard.getAvailableEndTime()) + "时间段的场馆费用支付");
                    }
                }
                if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){//折扣卡 ,储值折扣打折
                    //取折扣
                     discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount().intValue());
                    //打折扣
                    totalPrice = notMemberPrice.multiply(discount.divide(new BigDecimal(100)));
                }
            }
        }
        
        
        //插入父订单
        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = new TbBizPlacePrivateOrder();
        tbBizPlacePrivateOrder.setPlaceOrderId(orderid);
        tbBizPlacePrivateOrder.setCategoryId(reqBillingInfo.getCategoryId());
        tbBizPlacePrivateOrder.setCustomerName(StringUtils.isEmpty(reqBillingInfo.getName()) ? "散客":reqBillingInfo.getName());
        tbBizPlacePrivateOrder.setMobile(reqBillingInfo.getContactInformation());
        tbBizPlacePrivateOrder.setDescrible(reqBillingInfo.getMemo());
        tbBizPlacePrivateOrder.setPlaceId(reqBillingInfo.getPlaceId());
        tbBizPlacePrivateOrder.setCreateUid(reqBillingInfo.getCreateUid());
        //tbBizPlacePrivateOrder.setPaymentTime(new Date());
        tbBizPlacePrivateOrder.setDebit(new BigDecimal(0));//预定 收入为0
        tbBizPlacePrivateOrder.setDate(new Date());
        //tbBizPlacePrivateOrder.setEndTime(new Date());
        tbBizPlacePrivateOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
        tbBizPlacePrivateOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        tbBizPlacePrivateOrder.setOrderStatusChangeDate(new Date());
        tbBizPlacePrivateOrder.setParentId(0);
        tbBizPlacePrivateOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);
        tbBizPlacePrivateOrder.setStartDate(DateUtils.transferLongToDate(reqBillingInfo.getStartDate()));
        tbBizPlacePrivateOrder.setEndDate(DateUtils.transferLongToDate(reqBillingInfo.getEndDate()));
        tbBizPlacePrivateOrder.setWeeks(JSON.toJSONString(reqBillingInfo.getWeek()));
        //tbBizPlacePrivateOrder.setHandAdjustAmount(new BigDecimal(reqBillingInfo.getReceivedAmount()).subtract(totalPrice));
        tbBizPlacePrivateOrder.setHandAdjustAmount(new BigDecimal(0));//预定不支持调价
        tbBizPlacePrivateOrder.setUseType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
        tbBizPlacePrivateOrder.setExpression(!StringUtils.isEmpty(reqBillingInfo.getExpression())? reqBillingInfo.getExpression() : "");
       
        //预定--设置为未支付状态
        tbBizPlacePrivateOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);
        tbBizPlacePrivateOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);

        
        Integer porderid = 0;
        if (this.tbBizPlacePrivateOrderMapper.insertSelective(tbBizPlacePrivateOrder) != 0) {
            porderid = tbBizPlacePrivateOrder.getId();
            logger.debug("========================插入父订单数据:tbBizPlacePrivateOrder:{}", JSON.toJSONString(tbBizPlacePrivateOrder));
        }
        //按日期插入订单明细数据
        reqBillingInfo.setParentOrderId(porderid);
        reqBillingInfo.setDiscount(discount.intValue());
        
        Map map = addBlockOrderDetail(tbBizPlaceUnitSalePlans, reqBillingInfo,  tbBizPlaceMemberCard);
        if (MapUtils.isEmpty(map)) {
            throw new Exception("生成子订单异常");
        }
        List<TbBizPlaceOrder> orders = new ArrayList<>();
        List<TbBizPlaceOrderItem> items = new ArrayList<>();
        List<TbBizPlaceOrderDiscountItem> discounts = new ArrayList<TbBizPlaceOrderDiscountItem>();
        List<TbBizPlacePayItem> pays = new ArrayList<>();

        orders = (List<TbBizPlaceOrder>) MapUtils.getObject(map, "orders");
        items = (List<TbBizPlaceOrderItem>) MapUtils.getObject(map, "items");
        discounts = (List<TbBizPlaceOrderDiscountItem>) MapUtils.getObject(map, "discounts");

        //调整金额  计算 -- 预定不支持金额调整
        //this.calcAmount(orders,items,pays,reqBillingInfo,tbBizPlacePrivateOrder);
        logger.info("=========开始写入子订单明细 : orders.size() :{}, items.size() :{}, discounts.size() :{}", orders.size(), items.size(), discounts.size());
        //写入子订单和明细
        boolean flag = addOrders(orders, items, null, discounts, reqBillingInfo, tbBizPlaceMemberCard !=null ? tbBizPlaceMemberCard.getMemberUid() : null);
        if (flag) {
        	//写入会员卡交易明细
        	if (tbBizPlaceMemberCard !=null) {
        		BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
    			BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
    			TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
    			tbBizPlaceMemberOpHistory.setCreateUid(reqBillingInfo.getCreateUid());
    			tbBizPlaceMemberOpHistory.setPlaceId(reqBillingInfo.getPlaceId());
    			tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
    			tbBizPlaceMemberOpHistory.setAmount(new BigDecimal(0));//预定初始为0
    			tbBizPlaceMemberOpHistory.setCreateTime(new Date());
    			tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());

    			tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqBillingInfo.getPlaceId()));
    			tbBizPlaceMemberOpHistory.setOrderNo(orderid);
    			tbBizPlaceMemberOpHistory.setOpTypeName("线下包场-" + iBaseService.getCommonDataCache("cagetory" + reqBillingInfo.getCategoryId().toString()) + "场地开单预订");
    			if (!org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getContactInformation()) && !org.springframework.util.StringUtils.isEmpty(reqBillingInfo.getName())) {
    				Integer uid = placeMemberService.getUidByNameAndPhone(reqBillingInfo.getName(), reqBillingInfo.getContactInformation());
    				tbBizPlaceMemberOpHistory.setUid(uid);
    			}
    			tbBizPlaceMemberOpHistory.setUserName(reqBillingInfo.getName());
    			tbBizPlaceMemberOpHistory.setMobile(reqBillingInfo.getContactInformation());
    			tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard.getCardName());
    			tbBizPlaceMemberOpHistory.setMemo(reqBillingInfo.getMemo());
    			tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
    			tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
    			tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);//预订流水记录无效
    			tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
    			tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
    			tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
    			tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
    			tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
    			tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard.getCardTypeId());

    			tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);

        	}

		} else {
			throw new Exception("包场预定失败");
		}
        return APIResponse.returnSuccess(tbBizPlacePrivateOrder);
    }
    
    private Map addBlockOrderDetail(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans,
                              ReqBillingInfo reqBillingInfo, TbBizPlaceMemberCard tbBizPlaceMemberCard) {
        List<TbBizPlaceOrder> orders = new ArrayList<>();
        List<TbBizPlaceOrderItem> items = new ArrayList<>();
        List<TbBizPlaceOrderDiscountItem> orderDiscounts = new ArrayList<TbBizPlaceOrderDiscountItem>();
        List<TbBizPlacePayItem> pays = new ArrayList<>();

        Date startDate = new Date(reqBillingInfo.getStartDate());
        Date endDate = new Date(reqBillingInfo.getEndDate());
        if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlans)) {
            //循环日期
            Calendar ca = Calendar.getInstance();
            Date curDate = startDate;
            Map<String, List<TbBizPlaceUnitSalePlan>> tbBizPlaceUnitSalePlansMap =
                    getTbBizPlaceUnitSalePlanListByDay(tbBizPlaceUnitSalePlans);

            while (curDate.compareTo(endDate) <= 0) {
                ca.setTime(curDate);
                Integer week = Integer.parseInt(DateUtils.dayForWeeks(DateUtils.transferDateToString(curDate)));
                if (reqBillingInfo.getWeek().contains(week)) {
                    List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanTemp = tbBizPlaceUnitSalePlansMap
                            .get(DateUtils.transferDateToString(curDate));
                    //按天生产订单
                    Map map = getBlockPlaceOrderByDay(curDate, tbBizPlaceUnitSalePlanTemp,reqBillingInfo,tbBizPlaceMemberCard);
                    if (MapUtils.isEmpty(map)) {
                        ca.add(Calendar.DATE, 1);
                        curDate = ca.getTime();
                        continue;
                    }
                    orders.add((TbBizPlaceOrder) MapUtils.getObject(map, "order"));
                    items.addAll((List<TbBizPlaceOrderItem>) MapUtils.getObject(map, "items"));
                    orderDiscounts.addAll((List<TbBizPlaceOrderDiscountItem>) MapUtils.getObject(map, "discounts"));
                }
                ca.add(Calendar.DATE, 1);
                curDate = ca.getTime();
            }

            Map map1 = new HashMap();
            map1.put("orders", orders);
            map1.put("items", items);
            map1.put("discounts", orderDiscounts);
            return map1;
        }
        return null;
    }
    
    private Map getBlockPlaceOrderByDay(final Date date,
            List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans,
            ReqBillingInfo reqBillingInfo,
            TbBizPlaceMemberCard tbBizPlaceMemberCard) {
    	
			Collection<TbBizPlaceUnitSalePlan> result = tbBizPlaceUnitSalePlans;
			if (CollectionUtils.isEmpty(result)) {
				return null;
			}
			
			BigDecimal price = new BigDecimal(0);
			BigDecimal notMemberPrice = new BigDecimal(0);
				
			String orderid = baseService.getBizOrderId(reqBillingInfo.getCreateUid());
			List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = new ArrayList<>();
			List<TbBizPlaceOrderDiscountItem> tbBizPlaceOrderDiscountItemList = new ArrayList<TbBizPlaceOrderDiscountItem>();

			// 生成订单明细
			for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : result) {

				TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
				tbBizPlaceOrderItem.setCreateTime(date);
				tbBizPlaceOrderItem.setUpdateTime(date);
				tbBizPlaceOrderItem.setPlaceOrderId(orderid);
				tbBizPlaceOrderItem.setVersion(tbBizPlaceUnitSalePlan.getVersion());
				
				//包场，散客还是按照原价，待付款调价的时候再做优惠
				if (tbBizPlaceMemberCard != null) {
					tbBizPlaceOrderItem.setSalePrice(tbBizPlaceUnitSalePlan.getMemberPrice()
							.multiply(new BigDecimal(reqBillingInfo.getDiscount()).divide(new BigDecimal(100))));
				} else {
					tbBizPlaceOrderItem.setSalePrice(tbBizPlaceUnitSalePlan.getPrice()
							.multiply(new BigDecimal(reqBillingInfo.getDiscount()).divide(new BigDecimal(100))));
				}
				tbBizPlaceOrderItem.setCreateUid(reqBillingInfo.getCreateUid());
				tbBizPlaceOrderItem.setSaleId(CommonUtils.createSaleID(tbBizPlaceUnitSalePlan.getPlaceUnitId(), tbBizPlaceUnitSalePlan.getDate(), tbBizPlaceUnitSalePlan.getStartTime(),tbBizPlaceUnitSalePlan.getEndTime()));
				
				tbBizPlaceOrderItem.setUnitSalePlanId(getPlaceSaleUnitId(tbBizPlaceOrderItem.getSaleId()));
				logger.info("======获取销售计划ID: Request : slaeId = {} ,Response : ID = {}",tbBizPlaceOrderItem.getSaleId(),tbBizPlaceOrderItem.getUnitSalePlanId());
				
				tbBizPlaceOrderItem.setConsumeTime(tbBizPlaceUnitSalePlan.getDate());
				tbBizPlaceOrderItem.setItemUuid(UUIDUtils.createId());
				tbBizPlaceOrderItem.setUseType(PlaceConstants.ORDER_USE_BLOCK_BOOKING);
				tbBizPlaceOrderItem.setGoodsId(tbBizPlaceUnitSalePlan.getId());
				tbBizPlaceOrderItem.setGoodsName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
				tbBizPlaceOrderItem.setSurplusGoodsCount(1);
				tbBizPlaceOrderItem.setTotalGoodsCount(1);
				tbBizPlaceOrderItem.setStartTime(tbBizPlaceUnitSalePlan.getStartTime());
				tbBizPlaceOrderItem.setEndTime(tbBizPlaceUnitSalePlan.getEndTime());
				tbBizPlaceOrderItem.setOriginPrice(tbBizPlaceUnitSalePlan.getPrice());
				tbBizPlaceOrderItem.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
				tbBizPlaceOrderItem.setStatus(PlaceConstants.ORDER_PREPAY_STATUS.intValue());
				tbBizPlaceOrderItem.setCategoryId(tbBizPlaceUnitSalePlan.getCategoryId());

				tbBizPlaceOrderItemList.add(tbBizPlaceOrderItem);
				price = price.add(tbBizPlaceUnitSalePlan.getMemberPrice()
				.multiply(new BigDecimal(reqBillingInfo.getDiscount()).divide(new BigDecimal(100))));
				notMemberPrice = notMemberPrice.add(tbBizPlaceUnitSalePlan.getPrice());

				//会员单   则写入订单明细优惠 -- 支付的时候再去写入
//				if (tbBizPlaceMemberCard != null) {
//					TbBizPlaceOrderDiscountItem orderDiscountItem = new TbBizPlaceOrderDiscountItem();
//					orderDiscountItem.setPlaceOrderId(orderid);
//					orderDiscountItem.setOrderItemUuid(tbBizPlaceOrderItem.getItemUuid());
//					orderDiscountItem.setStatus(PlaceConstants.ORDER_PREPAY_STATUS.intValue());
//					orderDiscountItem.setMemberCardNo(tbBizPlaceMemberCard.getInnerCardNo());
//					orderDiscountItem.setCreateTime(new Date());
//					orderDiscountItem.setUpdateTime(new Date());
//
//					BigDecimal discountPrice = tbBizPlaceOrderItem.getOriginPrice().subtract(tbBizPlaceOrderItem.getSalePrice());
//				    if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){//折扣卡 ,储值折扣打折
//				    	orderDiscountItem.setDiscountMember(discountPrice);
//				    	orderDiscountItem.setDiscountDiscountMember(discountPrice);
//	                } else {
//	                	orderDiscountItem.setDiscountMember(discountPrice);
//	                }
//					tbBizPlaceOrderDiscountItemList.add(orderDiscountItem);
//				}
			}
				
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			
			//插入日订单
			TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();
			tbBizPlaceOrder.setPlaceOrderId(orderid);
			tbBizPlaceOrder.setUseType(new Byte(PlaceConstants.PRIVATE_USE_TYPE + ""));
			tbBizPlaceOrder.setCategoryId(reqBillingInfo.getCategoryId());
			tbBizPlaceOrder.setCustomerName(StringUtils.isEmpty(reqBillingInfo.getName()) ? "散客":reqBillingInfo.getName());
			tbBizPlaceOrder.setMobile(reqBillingInfo.getContactInformation());
			tbBizPlaceOrder.setDescrible(reqBillingInfo.getMemo());
			tbBizPlaceOrder.setPlaceId(reqBillingInfo.getPlaceId());
			tbBizPlaceOrder.setCreateUid(reqBillingInfo.getCreateUid());
			tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);
			tbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
			//tbBizPlaceOrder.setPaymentTime(date);
			tbBizPlaceOrder.setDebit(notMemberPrice);
			tbBizPlaceOrder.setDate(date);
			//tbBizPlaceOrder.setEndTime(date);
			tbBizPlaceOrder.setUpdateTime(date);
			tbBizPlaceOrder.setCreateTime(date);
			tbBizPlaceOrder.setOrderTime(date);
			tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
			tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
			tbBizPlaceOrder.setOrderStatusChangeDate(date);
			tbBizPlaceOrder.setParentId(reqBillingInfo.getParentOrderId());
			tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);
			tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
			tbBizPlaceOrder.setEnableRefund(reqBillingInfo.getEnableRefund().byteValue());

			if (null != tbBizPlaceMemberCard){
				tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
				tbBizPlaceOrder.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
			}else{
				tbBizPlaceOrder.setIsMember(PlaceConstants.NO);
			}
			
			if (!StringUtils.isEmpty(reqBillingInfo.getExpression())){
				tbBizPlaceOrder.setExpression(reqBillingInfo.getExpression());
			}else{
				tbBizPlaceOrder.setExpression("");
			}
			
			//场馆运营模式
			TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqBillingInfo.getPlaceId());
			tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

			Map map = new HashMap();
			map.put("order", tbBizPlaceOrder);
			map.put("items", tbBizPlaceOrderItemList);
			map.put("discounts", tbBizPlaceOrderDiscountItemList);
			return map;
		}

	}
